* 类加载器
* Java虚拟机中可以安装多个类加载器,系统默认三个主要类加载器,每个类负责加载特定位置的类:* BootStrap,ExtClassLoader,AppClassLoader
*
* 类加载器也是Java类,因为其他是java类的类加载器本身也要被类加载器加载,显然必须有第一
* 个类加载器不是java类,这正是BootStrap
* ExtClassLoader:JRE/lib/ext/*.jar包的类加载器
* AppClassLoader:CLASSPATH指定的所有jar或目录
*
* 所有类加载器采用具有父子关系的树形机构进行组织,在实例化每个类加载器对象时,需要为其指定
* 一个父级类加载器对象或者默认采用系统类加载器为其父级类加载
package cn.baidu.com;
public class ClassLoadTest {
public static void main(String[] args) {
System.out.println(
ClassLoadTest.class.getClassLoader().getClass().getName());
System.out.println(
System.class.getClassLoader()
);
ClassLoader loader =ClassLoadTest.class.getClassLoader();
while(loader!=null)//
{
System.out.println(loader.getClass().getName());
loader=loader.getParent();//它的父类加载器
}
System.out.println(loader);//BootStrap类加载器,这里输出为null
System.out.println(new ClassLoaderAttachment().toString());
Class d1=new MyClassLoader("itcastlib").loadClass("cn.itCast.day2.ClassLoaderAttachment");
Date d1=(Date)clazz.newInstance();
System.out.println(d1);
}
}
类加载器之间的继承关系:AppClassLoader->ExtClassLoader->BootStrap
类加载的具体执行过程和委托加载机制:由子类加载器委托给上级加载器,直至BootStrap,由BootStrap
进行加载,如果没有加载到类,回到发起者类加载器加载,还加载不到,抛出ClassNotFoundException
自己写加载器 MyClassLoader
package cn.baidu.com;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class MyClassLoader extends ClassLoader {
public static void main(String[] args) throws Exception {
String srcPath=args[0];
String desDir=args[1];
FileInputStream fis=new FileInputStream(srcPath);
String destFileName=srcPath.substring(srcPath.lastIndexOf('\\')+1);
String destPath =desDir+"\\"+destFileName;
FileOutputStream fos=new FileOutputStream(destPath);
cypher(fis,fos);
fis.close();
fos.close();
}
private static void cypher(InputStream ips,OutputStream ops) throws Exception
{
int b=-1;
while((b = ips.read())!=-1)
{
ops.write(b^0xff);
}
}
private String classDir;
//覆盖ClassLoader中的findClass方法
protected Class<?> findClass(String name) throws ClassNotFoundException
{
String classFileName=classDir+"\\"+name.substring(name.lastIndexOf('.')+1)+".class";
try {
FileInputStream fis = new FileInputStream(classFileName);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
cypher(fis,bos);
fis.close();
byte[] bytes=bos.toByteArray();
return defineClass(bytes,0,bytes.length);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.findClass(classFileName);
}
public MyClassLoader()
{
}
public MyClassLoader(String classDir)
{
this.classDir=classDir;
}
}
public class ClassLoaderAttachment extends Date {
public String toString()
{
return "hello,itcast";
}
}