【发布时间】: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