【发布时间】:2018-03-14 05:08:43
【问题描述】:
我必须使用第 3 方平台,但该平台有无法替换的旧版本 jar libjar-1.0.0.jar。该平台让我在其上运行我自己的(平面文件)包。我将新版本的libjar-2.0.0.jar 放在我的包/packages/package-name/external-jar 下。当我使用URLClassLoader 加载libjar-2.0.0.jar 然后打印出所有声明的方法时,我能够看到2.0.0 jar 中的方法。但是,当我调用时,我总是得到NoSuchMethodException。当我打印出 newobj.class.getProtectionDomain().getCodeSource().getLocation().toString() 时,它总是显示 libjar-1.0.0.jar 。谁能帮助解释我做错了什么以及在运行时强制使用特定 jar 中的类需要做什么?
这是我的代码快照
File f = new File(path);
URL[] urls = new URL[1];
urls[0] = f.toURI().toURL();
ClassLoader cl = new URLClassLoader(urls);
Class<?> utilsClass = cl.loadClass("com.myclass");
Constructor<?> cons = utilsClass.getConstructor(First.class, Second.class);
Object utils = cons.newInstance(firstObj, new Second());
if (utilsClass.getProtectionDomain() != null) {
LOGGER.info(utilsClass.getProtectionDomain().getCodeSource().getLocation().toString());
}
// this print out --- 1.0.0.jar instead of 2.0.0.jar
for (Method m : utilsClass.getDeclaredMethods()) {
LOGGER.info("methods: " + m.getName());
}
// method shows the "methodILookFor"
Method m = utilsClass.getDeclaredMethod("methodILookFor", Target.class, String[].class, Object.class);
// always throws NoSuchMethodException
m.invoke(utils, target, string, obj);
【问题讨论】:
-
您是否使用 Maven 来构建您的项目?
-
没有。这是来自第 3 方平台的 make 文件。
标签: java classloader