(1)使用类加载器获取类对象
Class clazz=Claass.forName(“com.zking.entity.Person”);
(2)查看类对象的类加载器
ClassLoader classLoader=class.getClassLoader(); App
ClassLoader classLoaderParent=classLoader.getParent(); Ext
ClassLoader classLoaderGrandParent=classLoaderParent.getParent(); null
2、类加载器的类型
<1>应用类加载器App:加载自己写的类或者jar包下面的类
<2>加载jdk/jre/lib/ext/下面的所有jar包
<3>根类加载器null:加载jdk/jre/lib/jar(所有类加载器的父加载器)
3、自定义类加载器
新建一个类用来加载对象
public class TestClassLoader {
@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();
}
}
/**
* 自定义类加载器
* @author Administrator
*
*/
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="D:\\桌面文件\\桌面\\"+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;
}
}