java
复制代码
//实现自定义类加载器
package com.chapter11;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class MyClassLoader extends ClassLoader {
private String byteCodePath;
public MyClassLoader(String byteCodePath) {
this.byteCodePath = byteCodePath;
}
public MyClassLoader(ClassLoader parent, String byteCodePath) {
super(parent);
this.byteCodePath = byteCodePath;
}
@Override
protected Class<?> findClass(String className) throws ClassNotFoundException {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
try {
//获取字节码文件完整路径
String fileName = byteCodePath + className + ".class";
//获取一个输入流
bis = new BufferedInputStream(new FileInputStream(fileName));
//获取输出流
baos = new ByteArrayOutputStream();
//具体读入数据并写出过程
int len;
byte[] data = new byte[1024];
while ((len = bis.read(data)) != -1) {
baos.write(data,0,len);
}
//获取内存中完整的字节数组的数据
byte[] byteCodes = baos.toByteArray();
//调用defineClass,将字节数组的数据转换为Class实例
Class<?> clazz = defineClass(null, byteCodes, 0, byteCodes.length);
return clazz;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
if (bis !=null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
//------
public class MyClassLoaderTest {
public static void main(String[] args) {
MyClassLoader loader = new MyClassLoader("d:/");
try {
Class<?> clazz = loader.loadClass("JavapTest");
System.out.println("加载此类的加载器为:" + clazz.getClassLoader().getClass().getName());
System.out.println("加载当前JavapTest类的加载器的父类加载器为:" + clazz.getClassLoader().getParent().getClass().getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
//-----测试结果
加载此类的加载器为:com.chapter11.MyClassLoader
加载当前JavapTest类的加载器的父类加载器为:sun.misc.Launcher$AppClassLoader