首页 > 编程知识 正文

输入要加载的自定义名称,java类加载器有什么用

时间:2023-05-05 21:49:44 阅读:11902 作者:2441

实现自定义类加载器(自定义文件系统类加载器)

package cn.com.lodar; import java.io.*; publicclassfilesystemclassloaderextendsclassloader//自定义文件系统类加载器私有字符串加载器; publicfilesystemclassloader (string rootdir ) { this.rootDir=rootDir; } @复盖保护类? 查找类(字符串名称) throwsclassnotfoundexception { class? c=findloadedclass(name; //查找此类//查找是否加载过此类,如果有,则返回加载的类,如果没有,则加载新的IF类(c!=null}{returnc; } else { class loader parent=this.get parent (; //获取父类的加载器try{c=parent.loadclass(name ); //委托加载到父类}catch(exceptione ) {//e.printStackTrace ); //c=Parent.loadclass(name ); if(c!=null}{returnc; } else { byte [ ] classdata=getclass data (name ); if(classdata==null ) { throw new classnotfoundexception (; }else{c=defineclass(name,classData,0,classData.length ); } }返回c; } private byte [ ] getclass data (string class name ) (string path=rootdir '/' class name.replace ).class )、(()/字节输出流baos=null; try{is=newfileInputstream(path ); baos=new ByteArrayOutputStream (; byte[] bytes=new byte[1024]; int tmp; while(tmp=is.read ) bytes )!=-1 ) Baos.write(bytes,0,tmp ); } baos.flush (; return baos.toByteArray (; }catch(exceptione ) { e.printStackTrace ); (Finally ) if(is!=null () try ) is.close ); }catch(ioexceptione ) { e.printStackTrace ); } }返回空值; }测试用例

package cn.com.lodar; publicclasstestfilesystemclassloader { publicstaticvoidmain { string [ ] args } throwsclassnotfoundexception {文件系统类Class? c=loader.load class (cn.com.test.helloword ); Class? C2=loader.load class (cn.com.test.helloword ); Class? C3=loader1. load class (cn.com.test.helloword ); Class? C4=loader1. load class (Java.lang.string ); Class? C5=loader1. load class (cn.com.lo Dar.demo 02 ); //system.out.println(c; system.out.println(c.hashcode ); //只有当相同的类加载器加载相同的类时,JVM才会识别为相同的类system.out.println (C2.hashcode ); system.out.println(C3.hashcode ); //JVM不是同一类加载器加载同一类,而是不同的类system.out.println(C4.hashcode ) ) ) ) ) ) ) system //自定义类加载器system.out.println (C4.getclass loader () ); //引导装载器system.out.println (C5.getclass loader () ); //系统默认类加载器}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。