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

我有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"); } } 

从这个线程我得知这必须被这样的东西取代:

 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(classpath, true, loader);

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

Class.forName(String name, boolean initialize, ClassLoader loader)的文档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的主类替换。