【问题标题】:Java 9 - add jar dynamically at runtimeJava 9 - 在运行时动态添加 jar
【发布时间】:2018-06-27 13:53:53
【问题描述】:

我遇到了 Java 9 的类加载器问题。

此代码适用于以前的 Java 版本:

 private static void addNewURL(URL u) throws IOException {
    final Class[] newParameters = new Class[]{URL.class};
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class newClass = URLClassLoader.class;
    try {
      Method method = newClass.getDeclaredMethod("addNewURL", newParameters );
      method.setAccessible(true);
      method.invoke(urlClassLoader, new Object[]{u});
    } catch (Throwable t) {
      throw new IOException("Error, could not add URL to system classloader");
    }
  }

this thread 我了解到必须将其替换为以下内容:

Class.forName(classpath, true, loader);

loader = URLClassLoader.newInstance(
            new URL[]{u},
            MyClass.class.getClassLoader()

MyClass 是我尝试在其中实现Class.forName() 方法的类。

u = file:/C:/Users/SomeUser/Projects/MyTool/plugins/myNodes/myOwn-nodes-1.6.jar

String classpath = URLClassLoader.getSystemResource("plugins/myNodes/myOwn-nodes-1.6.jar").toString();

出于某种原因 - 我真的不知道为什么 - 我在运行 Class.forName(classpath, true, loader); 时收到 ClassNotFoundException

有人知道我做错了什么吗?

【问题讨论】:

  • Class.forName 采用类名,而不是类路径。

标签: java jar classloader java-9 urlclassloader


【解决方案1】:

来自Class.forName(String name, boolean initialize, ClassLoader loader) 的文档:-

抛出ClassNotFoundException - 如果指定的类加载器无法定位该类

另外,请注意用于 API 的参数包括类的名称,类加载器使用该类返回类的对象。

给定类或接口的完全限定名称(与 getName 返回的格式相同),此方法会尝试定位、加载和链接类或接口。

在您的示例代码中,这可以修改为:

// Constructing a URL form the path to JAR
URL u = new URL("file:/C:/Users/SomeUser/Projects/MyTool/plugins/myNodes/myOwn-nodes-1.6.jar");

// Creating an instance of URLClassloader using the above URL and parent classloader 
ClassLoader loader = URLClassLoader.newInstance(new URL[]{u}, MyClass.class.getClassLoader());

// Returns the class object
Class<?> yourMainClass = Class.forName("MainClassOfJar", true, loader);

上面代码中的MainClassOfJar应替换为JAR的主类myOwn-nodes-1.6.jar

【讨论】:

    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多