一、类加载器
顾名思义就是用来加载类的工具
二、类加载器的类型
<1>应用类加载器App:加载自己写的类或者jar包下面的类
<2>扩展类加载器Ext:加载jdk/jre/lib/ext/下面的所有jar包
<3>根类加载器null:加载jdk/jre/lib/jar(所有类加载器的父加载器)
三、加载器的工作原理:委托、可见性、单一性
四、使用类加载器获取类对象
@Test
public void test3() throws InstantiationException, IllegalAccessException{
//使用自己的类加载器 加载对象
try {
Class clazz=Class.forName("com.zking.entity.Person", true, new ClassLoaderDIY());
System.out.println(clazz.newInstance());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
五、自定义类加载器
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
System.out.println("自定义类加载器");
System.out.println(name);
//所有的.替换成\
name=name.replaceAll("\\.", "/");
System.out.println("替换后:"+name);
//根据name找到桌面上 相对应的 person.class文件
String desktopPath="C:\\Users\\Administrator\\Desktop\\"+name+".class";
System.out.println(desktopPath);
try {
FileInputStream fis=new FileInputStream(desktopPath);
System.out.println(fis.available());
int len=0;
byte[] b=new byte[fis.available()];
len=fis.read(b);
return defineClass(null,b,0,len);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}