方法:
- 重写loadclass方法,不推荐因为会破坏双亲委派模型
- 重写findClass方法,推荐
public class MyClassLoader extends ClassLoader{
//1
private String codePath;
//2.
public MyClassLoader(ClassLoader parent, String codePath) {
super(parent);
this.codePath = codePath;
}
public MyClassLoader(String codePath) {
this.codePath = codePath;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
try {
//1.字节码路径
String fileName = codePath + name + ".class";
//获取输入流
bis = new BufferedInputStream(new FileInputStream(fileName));
//获取输出流
baos = new ByteArrayOutputStream();
//进行io读写
int len;
byte[] data = new byte[1024];
while ((len = bis.read(data)) != -1){
baos.write(data,0,len);
}
//获取内存中的字节数组
byte[] byteCode = baos.toByteArray();
//调用defineClass将字节数组转成Class对象
Class<?> defineClass = defineClass(null, byteCode, 0, byteCode.length);
//返回
return defineClass;
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭资源
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
public class String {
static {
System.out.println("自定义的String...");
}
}
测试:
public class MyClassLoaderTest {
public static void main(String[] args) {
MyClassLoader classLoader = new MyClassLoader("d:/");
try {
Class<?> clazz = classLoader.loadClass("String");
System.out.println("由:" + clazz.getClassLoader().getClass().getName() + "加载的");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
结果:
由:com.zzyuan.lagou.util2.MyClassLoader加载的