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