类加载器
得到类加载器的类名AppClassLoader
syso(ClassLoaderTest.class.getClassLoader().getClass().getName())
得到AppClassLoader这个类加载器的父类ExtClassLoader
loader=ClassLoaderTest.class.getClassLoader().getParent()
loader.getParent()//null得到最顶层的类加载器,该类加载器不是java
关系:
BootStrap,ExtClassLoader,AppClassLoader ---子孙三代
作用范围
AppClassLoader加载classPath指定的所有jar或者目录
ExtClassLoader加载JRE/lib/ext/*.jar
BootStrap加载JRE/lib/rt.jar
委托机制:如果父加载器能加载,则子加载器不用加载
自定义类加载器
1.定义测试待加载类
publicclass ClassLoaderAttachment extends Date{
publicString toString(){
return"xiekongying";
}
}
2.创建自己的带有加密功能的加载器
publicclass MyClassLoader extends ClassLoader{
/**
* @param args
*/
publicstatic void main(String[] args) throws Exception{
//TODO Auto-generated method stub
//使用args传递参数
StringsrcPath = "D:\\MyEclipse 8.5\\javaenhance\\bin\\com\\sdut\\day2\\ClassLoaderAttachment.class";
StringdescDir ="itcastlib";
//确定目的
StringdescRes =descDir+"\\"+srcPath.substring(srcPath.lastIndexOf("\\")+1);
FileInputStreamfis = new FileInputStream(srcPath);
FileOutputStreamfos = new FileOutputStream(descRes);
cypher(fis,fos);
fis.close();
fos.close();
}
//加密函数
publicstatic void cypher(InputStream ips,OutputStream ops) throws Exception{
intb = -1;
while((b= ips.read())!=-1){
ops.write(b^ 0xff);
//System.out.println(b);
}
ips.close();
ops.close();
}
privateString classDir;
@Override
protectedClass<?> findClass(String name) throws ClassNotFoundException {
//先去父类去找,找不到在找子类,name是找到要加载的类名
StringclassFileName = classDir + "\\" + name +".class";
//找到文件后,将该class文件加载到内存字节数组中
//这个是本加载器的作用
try{
FileInputStreamfis = new FileInputStream(classFileName);
ByteArrayOutputStreambais = new ByteArrayOutputStream();
cypher(fis,bais);
fis.close();
byte[]bytes = bais.toByteArray();//得到源class的字节数组
returndefineClass(bytes, 0, bytes.length);//得到字节码对象
}catch (FileNotFoundException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
returnsuper.findClass(name);
}
publicMyClassLoader(String classDir){
this.classDir= classDir;
}
publicMyClassLoader(){
}
}
3.主方法测试
publicstatic void main(String[] args) throws Exception {
//System.out.println(newClassLoaderAttachment().toString());
//使用该类加载器加载类
Classc1 = new MyClassLoader("itcastlib").loadClass("ClassLoaderAttachment");//得到字节码对象,加载类
Dated = (Date)c1.newInstance();//使用反射创建对象//有空看看为什么必须用父类接受
System.out.println(d);//
}