我在下面的路径中有一个TEST123.class。
d:/用户/ XXX /桌面/ SEM-材料在职/ SEM-材料在职/ SEM-材料freemarkerjob /目标/类/ COM /携程/市场/ SEM / freemarkerjob / dynamicjava /
然后我运行下面的try子句通过URLClassLoader加载类,但它给我异常ava.lang.NoClassDefFoundError:TEST123(错误的名称:,如何解决异常?
ava.lang.NoClassDefFoundError: TEST123 (wrong name: com/ctrip/market/sem/freemarkerjob/dynamicjava/TEST123)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
try {
URLClassLoader mycl = new URLClassLoader(new URL[] { new URL(
"file:///D:/Users/XXX/Desktop/sem-material-job/sem-material-job/sem-material-freemarkerjob/target/classes/com/ctrip/market/sem/freemarkerjob/dynamicjava/") });
Class c2 = mycl.loadClass("TEST123");
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:1)
您正在尝试加载课程TEST123
,但您的TEST123.class
文件包含课程com.ctrip.market.sem.freemarkerjob.dynamicjava.TEST123
。 TEST123.java
第一行的包裹是什么?将代码更改为
URLClassLoader mycl = new URLClassLoader(new URL[] {
new URL("file:///D:/Users/XXX/Desktop/sem-material-job/sem-material-job/sem-material-freemarkerjob/target/classes/") });
Class c2 = mycl.loadClass("com.ctrip.market.sem.freemarkerjob.dynamicjava.TEST123");
应该工作。
答案 1 :(得分:1)
我认为您必须将URL更改为指向类路径并按包名加载类,如此
URLClassLoader mycl = new URLClassLoader(new URL[] {
new URL("file:///D:/Users/XXX/Desktop/sem-material-job/sem-material-job/sem-material-freemarkerjob/target/classes/") });
Class c2 = mycl.loadClass("com.ctrip.market.sem.freemarkerjob.dynamicjava.TEST123");