我一直在使用CustomerClassLoader,因为我正在尝试将.class文件加载到JUnitCore.runClasses(...);
,但我收到以下错误
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: SimpleTest (wrong name: JUnit/SimpleTest)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at Java.CustomClassLoader.access$000(CustomClassLoader.java:16)
at Java.CustomClassLoader$1.run(CustomClassLoader.java:45)
at java.security.AccessController.doPrivileged(Native Method)
at Java.CustomClassLoader.findClass(CustomClassLoader.java:33)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
.....
我不知道是什么错,因为我传递了正确的类名和路径。这是我正在使用的代码
CustomClassLoader
import java.io.FileInputStream;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
public class CustomClassLoader extends ClassLoader {
String repoLocation = "C:/TempBINfolder/bin/JUnit/";
public CustomClassLoader() { }
public CustomClassLoader(ClassLoader parent) {
super(parent);
}
@Override
protected Class<?> findClass(final String name)
throws ClassNotFoundException {
AccessControlContext acc = AccessController.getContext();
try {
return (Class)AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public Object run() throws ClassNotFoundException {
FileInputStream fi = null;
try {
String path = name.replace('.', '/');
fi = new FileInputStream(repoLocation + path
+ ".class");
byte[] classBytes = new byte[fi.available()];
fi.read(classBytes);
return defineClass(name, classBytes, 0,
classBytes.length);
}catch(Exception e )
{
throw new ClassNotFoundException(name);
}
}
}, acc);
} catch (java.security.PrivilegedActionException pae) {
return super.findClass(name);
}
}
}
这就是我的称呼方式
ClassLoader cls= new CustomClassLoader(ClassLoader.getSystemClassLoader());
Class stringClass = null;
try {
stringClass = cls.loadClass("SimpleTest");
} catch (ClassNotFoundException ex) {
Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex);
}
try {
stringClass.newInstance();
} catch (InstantiationException ex) {
Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex);
}
JUnitCore.runClasses(stringClass);
有谁知道我收到此错误的原因?
答案 0 :(得分:1)
更改
stringClass = cls.loadClass("SimpleTest");
至
stringClass = cls.loadClass("JUnit.SimpleTest");
(即添加类文件的完全限定包名称)
和
String repoLocation = "C:/TempBINfolder/bin/JUnit/";
至
String repoLocation = "C:/TempBINfolder/bin/";
答案 1 :(得分:0)
您必须声明您的SimpleTest类在JUnit包中,但您尝试加载就像SimpleTest(没有包)一样。试试eiteher:
String repoLocation = "C:/TempBINfolder/bin/";
答案 2 :(得分:0)
班级名称应完全合格junit.samples.SimpleTest
stringClass = cls.loadClass("SimpleTest");
应该是
stringClass = cls.loadClass("junit.sample.SimpleTest");
答案 3 :(得分:-1)
有时这种情况发生在我身上,而且通常是通过干净的构建来解决的。如果这不起作用,我通常会重新启动IDE。