实现自定义类加载器
- 继承ClassLoader父类
- 要遵从双亲委派机制,重写findClass方法
- 不是重写loadClass方法,否则不会走双亲委派机制
- 读取类的字节码文件
- 调用父类的defineClass方法来加载类
- 使用者调用该类加载器的loadClass方法
class MyClassLoader extends ClassLoader {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String path = "file parent path" + name + ".class";
try {
byte[] bytes;
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
bytes = new byte[(int)f.length()];
fis.read();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new ClassNotFoundException("Class Not Found");
} catch (IOException e) {
throw new RuntimeException(e);
}
retuen defineClass(name, bytes, 0, bytes.length);
}
}