自定义类加载器
1.为什么要自定义ClassLoader
因为系统的ClassLoader只会加载指定目录下的class文件,如果你想加载自己的class文件,那么就可以自定义一个ClassLoader。而且我们可以根据自己的需求,对class文件进行加密和解密。
2.如何自定义ClassLoader
使用步骤:
1.新建一个类继承java.lang.ClassLoader类,重写它的findClass方法。
2.将class字节码数组转换为Class的实例,调用父类的defineClass方法。
3.调用loadClass方法即可。
public class CustomClassLoader extends ClassLoader {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// 此处可以加任何你想做的操作。
File file = new File("/Users/zzz/Desktop/classes/" + name.replaceAll("\\.", "/").concat(".class"));
try {
FileInputStream inputStream = new FileInputStream(file);
ByteOutputStream byteOutputStream = new ByteOutputStream();
int a = 0;
byte[] buffer = new byte[1024];
while ((a = inputStream.read(buffer)) != -1) {
byteOutputStream.write(buffer,0,a);
}
byte[] bytes = byteOutputStream.toByteArray();
inputStream.close();
byteOutputStream.close();
return defineClass(name,bytes,0,bytes.length);
} catch (IOException e) {
e.printStackTrace();
}
return super.findClass(name);
}
public static void main(String[] args) {
CustomClassLoader customClassLoader = new CustomClassLoader();
try {
// 通过loadclass调用我们自己的classloader。
Class<?> aClass = customClassLoader.loadClass("cn.zl.TestDemo");
final Object o = aClass.newInstance();
System.out.println(o);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
结果如下:
ps:在findClass方法中,可以添加任何操作,加解密等。