类加载器的层次结构:
引导类加载器(bootstrap class loader)
用来加载java的核心库(JAVA_HOME/jre/lib/rt.jar,或sun.boot.class.path路径下的内容),是用原生代码来实现的(C实现的),并不继承自java.lang.ClassLoader。
加载扩展类和应用程序类加载器,并指定它们的父类加载器。
扩展类加载器(extensions class loader)
用来加载java的扩展库(JAVA_HOME/jre/lib/ext public class FileSystemClassLoader extends ClassLoader{ private String rootDir; public FileSystemClassLoader(String rootDir) { this.rootDir = rootDir; } private byte[] getClassData(String classname){ //com.test.User -> rootDir/com/test/User String path = rootDir +"/"+classname.replace(".", "/")+".class"; //IOUtils 可以使用它将读取的流数据转换为字节数组 InputStream is = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ is = new FileInputStream(path); byte[] buffer = new byte[1024]; int temp = 0; while((temp=is.read(buffer))!=-1){ baos.write(buffer, 0, temp); } return baos.toByteArray(); }catch(Exception e){ e.printStackTrace(); return null; }finally{ try { if(is!=null) is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(baos!=null) baos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public Class> loadClass(String name) throws ClassNotFoundException { Class> c = findLoadedClass(name); //应该先查询有没有加载过这个类。已经加载,则直接返回加载好的类。 if(c!=null){ return c; }else{ ClassLoader parent = this.getParent(); try{ //System.out.println("hello"); c = parent.loadClass(name); //委派给父类加载 }catch(Exception e){ //e.printStackTrace(); } if(c!=null){ return c; }else{ byte[] classData = getClassData(name); if(classData==null){ throw new ClassNotFoundException(); }else{ c = defineClass(name, classData, 0, classData.length); } } } return c; } }
测试代码:
package com.test;
public class Demo03 {
public static void main(String[] args) throws Exception {
FileSystemClassLoader loader = new FileSystemClassLoader("D:/myJava");
FileSystemClassLoader loader2 = new FileSystemClassLoader("D:/myJava");
Class> c = loader.loadClass("com.test.Demos");
Class> c2 = loader.loadClass("com.test.Demos");
Class> c3 = loader2.loadClass("com.test.Demos");
Class> c4 = loader2.loadClass("java.lang.String");
Class> c5 = loader.loadClass("com.test.Demo");
System.out.println(c.hashCode()+" "+c.getClassLoader());
System.out.println(c2.hashCode()+" "+c2.getClassLoader());
System.out.println(c3.hashCode()+" "+c3.getClassLoader());
System.out.println(c4.hashCode()+" "+c4.getClassLoader());
System.out.println(c5.hashCode()+" "+c5.getClassLoader());
//System.out.println(.getClassLoader());
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



