类加载器

来源:互联网 发布:农村淘宝下载安装 编辑:程序博客网 时间:2024/06/06 18:13

一、类加载器的类型

              <1>应用类加载器App:加载自己写的类或者jar包下面的类
          <2>扩展类加载器Ext:加载jdk/jre/lib/ext/下面的所有jar包

          <3>根类加载器null:加载jdk/jre/lib/jar(所有类加载器的父加载器)


类加载器的工作原理:委托、可见性、单一性

二、使用类加载器获取类对象,查看类对象的类加载器

            首先写一个Person的实体类(省略不写),然后再进行测试
@Test
public void test2(){
//通过类加载器获取对象
try {
//获取类对象
Class clazz=Class.forName("com.zking.entity.Person");

//获取类加载器
ClassLoader classLoader=clazz.getClassLoader();
ClassLoader classLoaderParent=classLoader.getParent();
ClassLoader classLoaderGrandParent=classLoaderParent.getParent();

//查询该类加载器的类型
System.out.println(classLoader);
System.out.println(classLoaderParent);
System.out.println(classLoaderGrandParent);

// Person person=(Person) clazz.newInstance();
// person.setPname("李四");
// System.out.println(person.getPname());
} catch (Exception e) {
e.printStackTrace();

}

三、自定义类加载器

首先写一个Person的实体类(省略不写),然后使用自定义类加载器获取类对象
,进行测试
package com.veryedu.entity;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ClassLoaderDIY extends ClassLoader{
@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;
}

}


@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();
}
}