class Clazz2{
public static void main(String[] args) {
ClassLoader classLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
try {
FileInputStream fileInputStream = new FileInputStream("C:\Users\zsx\IdeaProjects\springrest\target\test-classes\Test0.class");
byte[] bytes = new byte[1024];
try {
int offset = fileInputStream.read(bytes);
return defineClass("Test0",bytes,0,offset);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
throw new RuntimeException("class not found");
}
// @Override
// protected Class<?> findClass(String name) throws ClassNotFoundException {
// try {
// FileInputStream fileInputStream = new FileInputStream("C:\Users\zsx\IdeaProjects\springrest\target\test-classes\Test0.class");
// byte[] bytes = new byte[1024];
//
// try {
// int offset = fileInputStream.read(bytes);
// return defineClass("Test0",bytes,0,offset);
// } catch (IOException e) {
// e.printStackTrace();
// }
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// throw new RuntimeException("class not found");
// }
};
try {
Class cl = classLoader.loadClass("Test0");
try {
Object obj = cl.newInstance();
System.out.println(obj instanceof Test0);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
代码如上,如果我不是重写findClass方法而是重写loadClass方法,不是就破坏了java的双亲委托机制了吗,那这时候我在loadClass里面不委托父加载器而是直接加载我本地的一些系统jar包比如rt.jar不是就不对了吗,java是如何检查这种问题的呢,在代码里我尝试着自己重写了loadClass方法,发现报Exception in thread "main" java.lang.ClassCircularityError: Test0这个错误,不知道他是怎么个过程,另外当加载器在尝试加载一个类的时候这个类的父类是如何加载处理的呢,谢谢。