Java 9 - 在运行时动态添加 jar

Java 9 - add jar dynamically at runtime

我遇到 classloader 问题 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 我正在尝试实现 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(String name, boolean initialize, ClassLoader loader) 的文档:-

throws ClassNotFoundException - if the class cannot be located by the specified class loader

此外,请注意用于 API 的参数包括 name 的 class 使用哪个classloader returns class.

的对象

Given the fully qualified name for a class or interface (in the same format returned by getName) this method attempts to locate, load, and link the class or interface.

在您的示例代码中,这可以纠正为类似这样的内容:

// 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 的主要 class .