问题描述
我遇到了Java 9的类加载器问题。
I've got a classloader problem with Java 9.
此代码适用于以前的Java版本:
This code worked with previous Java versions:
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");
}
}
来自我了解到这必须被这样的东西取代:
From this thread I learned that this has to be replaced by something like this:
Class.forName(classpath, true, loader);
loader = URLClassLoader.newInstance(
new URL[]{u},
MyClass.class.getClassLoader()
MyClass
是我正在尝试实现 Class.forName的类( )
方法。
MyClass
is the class I'm trying to implement the Class.forName()
method in.
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);
For some reason - I really can't figure out, why - I get a ClassNotFoundException when running Class.forName(classpath, true, loader);
有人知道我做错了吗?
推荐答案
来自: -
From the documentation of the Class.forName(String name, boolean initialize, ClassLoader loader)
:-
另外,请注意用于的参数API包含类的 名称,类加载器使用该名称返回类的对象。
Also, note the arguments used for the API includes the name of the class using which the classloader returns the object of the class.
在您的示例代码中,可以将其修改为:
In your sample code, this can be redressed to something like :
// 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 取代。
where MainClassOfJar
in the above code shall be replaced by the main class of the JAR myOwn-nodes-1.6.jar.
这篇关于Java 9 - 在运行时动态添加jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!