好的,基本上,我尝试使用这里描述的方法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;
}
}Main:
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到底做了什么)。
发布于 2018-09-03 23:21:24
好的,我从这个问题中得到答案:How to load all the jars from a directory dynamically?
并更改URL部分的开始与它的方式,在长的部分它的工作。
因此,一个示例可以是:
String path = "libs/dpr-common.jar";
if (new File(path).exists()) {
URL myJarFile = new File(path).toURI().toURL();
URL[] urls = { myJarFile };
URLClassLoader child = new URLClassLoader(urls);
Class DPRConfLoad = Class.forName("com.thales.atm.dpr.common.util.DPRConfigurationLoader", true, child);
Method method = DPRConfLoad.getDeclaredMethod("getInstance");
final Object dprConf = method.invoke(DPRConfLoad);
}我所有的时间都浪费在搜索上,而这是错误的例子……仍然不明白为什么他们使用像"jar:file...“这样愚蠢的URL。等。
谢谢大家。
https://stackoverflow.com/questions/52145561
复制相似问题