【发布时间】:2019-02-08 06:19:29
【问题描述】:
好的,基本上,我尝试使用这里描述的方法JarFileLoader 来加载一个包含一个类的 jar,该类的使用方式与类路径中的类相同(类名将是动态的,因此我们可以使用任何类添加任何 jar,程序将通过在主行中解析文本文件来加载它。
问题是当我调试和检查 URLClassLoader 对象时
protected Class<?> findClass(final String name)
行:
Resource res = ucp.getResource(path, false);
getResource() 在参数中找不到类名。
是否有人已经尝试过以这种方式加载 jar 文件?
谢谢。
加载器:
public class JarFileLoader extends URLClassLoader {
public JarFileLoader() {
super(new URL[] {});
}
public JarFileLoader withFile(String jarFile) {
return withFile(new File(jarFile));
}
public JarFileLoader withFile(File jarFile) {
try {
if (jarFile.exists())
addURL(new URL("file://" + jarFile.getAbsolutePath() + "!/"));
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
return this;
}
public JarFileLoader withLibDir(String path) {
Stream.of(new File(path).listFiles(f -> f.getName().endsWith(".jar"))).forEach(this::withFile);
return this;
}
}
主要:
public static void main(String[] args) {
new Initializer();
JarFileLoader cl = new JarFileLoader();
cl = cl.withFile(new File("libs/dpr-common.jar"));
try {
cl.loadClass("com.*****.atm.dpr.common.util.DPRConfigurationLoader");
System.out.println("Success!");
} catch (ClassNotFoundException e) {
System.out.println("Failed.");
e.printStackTrace();
} finally {
try {
cl.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里是我使用的测试类。当我调试 URLClassLoader 时,我可以在第三个循环中看到 jar 文件的路径(循环在类路径和您在此处添加的 URL),但仍然找不到 ressource(并且无法调试类 URLClassPath 所以不知道 getRessource 做了什么确切地说)。
【问题讨论】:
-
也试过这个:JarFileLoader 没有任何改变。
-
如果您希望我们帮助您调试代码,您将不得不提供代码的更多详细信息。理想情况下,以 Java 主程序或 JUnit 测试的形式提供重现。它会有依赖关系,但你可以解释这些。
-
目前尚不清楚从 Jar 文件加载类是否有效,或者仅从 Jar 文件加载资源是否会导致问题。也许你在加载资源时只是有一个path issue
-
我刚刚找到一篇关于我现在将尝试的帖子。如果它有效,我将关闭这个问题。 :-) stackoverflow.com/questions/21904219/…
-
好吧,简单的方法是错误的,但经过更正后它终于可以工作了!我不知道为什么示例是错误的,而用循环等解释的长方法是正确的......所以唯一要做的就是在文件上使用内部方法 toURL 就是这样......
String path = "libs/dpr-common.jar"; if (new File(path).exists()) URL myJarFile = new File(path).toURI().toURL();
标签: java urlclassloader