12_类加载器与类初始化深度剖析
可以用-XX:+TraceClassLoading虚拟机参数来查看类加载的顺序。
class Parent{
static int a = 3;
static {
System.out.println("Parent static Bbolck");
}
}
class Child extends Parent{
static int b = 4;
static {
System.out.println("Child static block");
}
}
public class MyTest9 {
static {
System.out.println("MyTest9 static block");
}
public static void main(String[] args) {
System.out.println(Child.b);
}
}
输出:
[Loaded top.tomxwd.classloader.MyTest9 from file:/E:/IDEA-workspace/jvm-test-01/target/classes/]
MyTest9 static block
[Loaded top.tomxwd.classloader.Parent from file:/E:/IDEA-workspace/jvm-test-01/target/classes/]
[Loaded top.tomxwd.classloader.Child from file:/E:/IDEA-workspace/jvm-test-01/target/classes/]
Parent static Bbolck
Child static block
4
代码:
public class MyTest10 {
static {
System.out.println("MyTest10 static block");
}
public static void main(String[] args) {
Parent2 parent2;
System.out.println("------------------------------");
parent2 = new Parent2();
System.out.println("------------------------------");
System.out.println(parent2.a);
System.out.println("------------------------------");
System.out.println(Child2.b);
}
}
class Parent2 {
static int a = 3;
static {
System.out.println("Parent2 static block");
}
}
class Child2 extends Parent2{
static int b = 4;
static {
System.out.println("Child2 static block");
}
}
结果:
MyTest10 static block
------------------------------
Parent2 static block
------------------------------
3
------------------------------
Child2 static block
4
代码:
public class MyTest11 {
public static void main(String[] args) {
System.out.println(Child3.a);
Child3.doSomething();
}
}
class Parent3{
static int a = 3;
static {
System.out.println("Parent3 static block");
}
static void doSomething(){
System.out.println("do something");
}
}
class Child3 extends Parent3 {
static {
System.out.println("Child3 static block");
}
}
输出:
Parent3 static block
3
do something
谁拥有这个静态变量,就对谁主动使用,所以并没有初始化Child3。
代码:
public class MyTest12 {
public static void main(String[] args) throws ClassNotFoundException {
// 系统类加载器--应用类加载器
ClassLoader loader = ClassLoader.getSystemClassLoader();
Class<?> cl = loader.loadClass("top.tomxwd.classloader.CL");
System.out.println(cl);
System.out.println("----------------------------");
cl = Class.forName("top.tomxwd.classloader.CL");
System.out.println(cl);
}
}
class CL{
static {
System.out.println("Class CL");
}
}
输出:
class top.tomxwd.classloader.CL
----------------------------
Class CL
class top.tomxwd.classloader.CL
加载并不会进行初始化,只有主动使用的时候会,而上面是通过反射对CL进行主动使用。
调用ClassLoader类的loadClass方法加载一个类,并不是对类的主动使用,所以不会导致类的初始化。
评论区