我的程序如下:
package classloader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class ReloaderClass extends ClassLoader { private String classpath; private String className = "com.hgf.Cifa"; public ReloaderClass(String classpath) { this.classpath = classpath; } protected Class findClass(String name) throws ClassNotFoundException { Class aClass= findLoadedClass(name); if(aClass!=null){ return aClass; }else{ byte[] classData = getData(name); if (classData == null) { throw new ClassNotFoundException(); } else { return defineClass(this.className, classData, 0, classData.length); } } } private byte[] getData(String className) { String path = this.classpath+className; try { InputStream in = new FileInputStream(path); ByteArrayOutputStream stream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int num = 0; while ((num = in.read(buffer)) != -1) { stream.write(buffer, 0, num); } return stream.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { try { ReloaderClass reloader = new ReloaderClass("E:/com/hgf/"); Class r = reloader.findClass("Cifa.class"); System.out.println(r.newInstance()); System.out.println("再次加载"); ReloaderClass reloader2 = new ReloaderClass("E:/com/hgf/"); Class r2 = reloader.findClass("Cifa.class"); System.out.println(r2.newInstance()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
报错如下:
Cifa@1012ddd 再次加载 Exception in thread "main" java.lang.LinkageError: loader (instance of classloader/ReloaderClass): attempted duplicate class definition for name: "Cifa" at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:760) at java.lang.ClassLoader.defineClass(ClassLoader.java:642) at classloader.ReloaderClass.loadClass(ReloaderClass.java:29) at classloader.ReloaderClass.main(ReloaderClass.java:60)
为什么
可能是这个问题
ReloaderClassreloader=newReloaderClass("E:/com/hgf/");// reloader
Classr=reloader.findClass("Cifa.class"); Classr2=reloader.findClass("Cifa.class");//这里应该是relaoder2吧确实。谢谢了~版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。