一、问题复现 先看下面的代码,第5行:new URLClassLoader(new URL[]{new URL(jarPath)});
URLClassLoader urlClassLoader =null;
Class<?> CompareUtil = null;
String jarPath = "https://aaa.bb.cc/x.jar";
try {
urlClassLoader = new URLClassLoader(new URL[]{new URL(jarPath)});
CompareUtil = urlClassLoader.loadClass("script.DraftablePublic");
Object instance = CompareUtil.newInstance();
Method method = CompareUtil.getMethod("compare", String.class, String.class);
return method.invoke(instance, source, target).toString();
} catch (Exception e) {
e.printStackTrace();
}
二、本地debug和打包后运行的区别 本地运行上面的代码没有任何问题,但是打包后会报错:NoClassDefFoundError 可能是由于java本身多线程机制引起的
三、解决 同样是第2行,改为:new URLClassLoader(new URL[]{new URL(jarPath)}, Thread.currentThread().getContextClassLoader());
这里指定使用当前线程进行处理
四、问题解决