我有一个类,并且我想通过绝对路径加载该类,但是我正在收到ClassNotFoundException.我经历过很多这样的线程,发现从绝对路径加载类是不正确的.
InputStream stream = new Check().getClass().getResourceAsStream(clazz+".class");
OutputStream os = new FileOutputStream(new File("D:\\deep.class"));
byte[] array = new byte[100];
while(stream.read(array) != -1){
os.write(array);
}
os.close();
stream.close();
Object obj = Class.forName("D:\\deep.class").newInstance();//getting exception here
System.out.println(obj instanceof Check);
解决方法:
在此用例中,您需要使用URLClassLoader来加载类
URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[] {
new URL(
"file:///D:/"
)
});
Class clazz = urlClassLoader.loadClass("deep");
标签:java,classloader
来源: https://codeday.me/bug/20191121/2048731.html