Class.forName() 与 ClassLoader.loadClass() 这两种方式可以动态加载一个类,区别是:
demo 演示上述介绍。
public class ClassLoadTest {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println("Class.forName 方式加载类--->start");
Class.forName("classtest.classloader.MyClassForName").getClass();
System.out.println("Class.forName 方式加载类--->end");
System.out.println("ClassLoader 方式加载类--->start");
Class<?> bClass = ClassLoader.getSystemClassLoader().loadClass("classtest.classloader.MyClassLoader");
System.out.println("ClassLoader 方式加载类--->end");
}
}
public class MyClassForName {
static {
System.out.println("MyClassForName static method execute");
}
}
public class MyClassLoader {
static {
System.out.println("MyClassLoader static method execute");
}
}
运行结果符合预期。
Class.forName 方式加载类--->start
MyClassForName static method execute
Class.forName 方式加载类--->end
ClassLoader 方式加载类--->start
ClassLoader 方式加载类--->end
ClassLoader 的双亲委派模型就不提了。
当一个类被显示使用时,JVM 会对其进行初始化,如下六种情况为显示使用: