示例代码(自定义类加载器)
public class MyClassLoader extends ClassLoader {
private String path="C:/Users/Administrator/Desktop/home/luciel/"; //默认加载路径
private String name; //类加载器名称
private final String filetype=".class"; //文件类型
/**
* 这个构造方法中去调用ClassLoader无参构造方法从ClassLoader源码中可以得出:
* 调用此构造方法会让系统类加载器成为该类加载器的父加载器。
* @param name
*/
public MyClassLoader(String name) {
// TODO Auto-generated constructor stub
super();
this.name=name;
}
public MyClassLoader(ClassLoader parent,String name){
super(parent);
this.name=name;
}
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
// TODO Auto-generated method stub
byte[] b=loadClassData(name);
return defineClass(name, b, 0, b.length);
}
private byte[] loadClassData(String name) {
byte[] data=null;
InputStream in=null;
name=name.replace('.', '/');
ByteArrayOutputStream out=new ByteArrayOutputStream();
try {
in=new FileInputStream(new File(path+name+filetype));
int len=0;
while(-1!=(len=in.read())){
out.write(len);
}
data=out.toByteArray();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return data;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.name;
}
}
public class Color {
public Color() {
System.out.println("Color is loaded by "+ this.getClass().getClassLoader());
}
}
public class Red extends Color {
public Red() {
System.out.println("Red is loaded by "+ this.getClass().getClassLoader());
}
}
public class TestMyClassLoader {
public static void main(String[] args) throws Exception {
MyClassLoader loader1 = new MyClassLoader("loader1");
loader1.setPath("C:/Users/Administrator/Desktop/home/luciel/test1/");
MyClassLoader loader2 = new MyClassLoader(loader1, "loader2");
loader2.setPath("C:/Users/Administrator/Desktop/home/luciel/test2/");
MyClassLoader loader3 = new MyClassLoader(null, "loader3");
loader3.setPath("C:/Users/Administrator/Desktop/home/luciel/test3/");
loadClassByMyClassLoader("com.demo.tcp.kaka.Red", loader2);
loadClassByMyClassLoader("com.demo.tcp.kaka.Red",loader3);
}
private static void loadClassByMyClassLoader(String name, ClassLoader loader) throws Exception {
Class<?> c = loader.loadClass(name);
Object obj = c.newInstance();
}
}
测试结果
Color is loaded by loader1
Red is loaded by loader1
Color is loaded by loader3
Red is loaded by loader3
注意事项
-
按照main方法中给三个类加载器传入的路径创建相应的环境,并将Red、Color的class类拷贝到home/luciel/test1/和home/luciel/test2/以及home/luciel/test3/目录中,将TestMyClassLoader类和MyClassLoader拷贝home/luciel/main/ 中,并在该目录下执行java 包名.TestMyClassLoader
结果分析