public class MyCat {
public MyCat(){
System.out.println("MyCat is loaded by: " + this.getClass().getClassLoader());
}
}
public class MySample {
public MySample(){
System.out.println("MySample is loaded by: " + this.getClass().getClassLoader());
new MyCat();
}
}
public class MyTest17 {
public static void main(String[] args) throws Exception{
// 将系统类加载器当做loader1的父加载器
MyTest16 loader1 = new MyTest16("loader1");
Class<?> clazz = loader1.loadClass("com.yshuoo.jvm.classloader.MySample");
System.out.println("class: " + clazz.hashCode());
/**
* 如果注释掉该行,那么并不会实例化MySample对象,即MySample构造方法不会被调用
* 因此不会实例化MyCat对象,即没有对MyCat进行主动使用,对于这个例子不会加载MyCat Class
*/
Object object = clazz.newInstance();
}
}
可以使用-XX:+TraceClassLoading参数去运行验证到底有没有加载