开发者社区> 问答> 正文

热加载问题,求大神帮助看看~拜托了?报错

我的程序如下:
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)



为什么




展开
收起
爱吃鱼的程序员 2020-06-09 16:11:46 1021 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    可能是这个问题


     ReloaderClassreloader=newReloaderClass("E:/com/hgf/");// reloader 

     Classr=reloader.findClass("Cifa.class"); Classr2=reloader.findClass("Cifa.class");//这里应该是relaoder2吧确实。谢谢了~
    2020-06-09 16:12:04
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Storm源码走读笔记 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载