Java 9 - 在运行时动态添加jar [英] Java 9 - add jar dynamically at runtime
问题描述
我遇到了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);
有人知道我做错了吗?
推荐答案
来自 Class.forName(String nam e,布尔初始化,ClassLoader加载器)
: -
From the documentation of the Class.forName(String name, boolean initialize, ClassLoader loader)
:-
抛出
ClassNotFoundException
- 如果指定的类加载器无法找到该类
throws
ClassNotFoundException
- if the class cannot be located by the specified class 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.
给定类或接口的完全限定名称(采用getName返回的相同格式),此方法尝试查找,加载和链接类或接口。
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.
在您的示例代码中,可以将其修改为:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!