分析类初始化

HeJin大约 2 分钟Java注解和反射

什么时候会发生类初始化

  • 类的主动引用(一定会发生类的初始化)
    • 当虚拟机启动时,先初始化main方法所在的类
    • new一个类的对象
    • 调用类的静态成员(除了final常量)和静态方法
    • 使用java.lang.reflect包的方法对类进行反射调用
    • 当初始化一个类,如果其父类没有被初始化,则会先初始化它的父类
  • 类的被动引用(不会发生类的初始化)
    • 当访问一个静态域时,只有真正声明这个域的类才会被初始化。如:当通过子类引用父类的静态变量,不会导致子类初始化。
    • 通过数组定义类引用,不会触发此类的初始化。
    • 引用常量不会触发此类的初始化(常量在链接阶段就存入类的常量池中了)

主动引用测试

new一个类

package com.hejin.reflection;

/**
 * @Description 类什么时候会初始化
 * @Author Administrator
 * @Date 2020/12/2 9:51
 */
public class Test06 {

    static {
        System.out.println("Main类被加载");
    }

    public static void main(String[] args) throws ClassNotFoundException {
        /**
         * 1、new
         */
        Son son = new Son();
    }

}

class Father{

    static int b = 2;

    static {
        System.out.println("父类被加载");
    }

}

class Son extends Father {
    static {
        System.out.println("子类被加载");
        m = 300;
    }

    static int m = 100;
    static final int M = 1;
}

结果

Main类被加载
父类被加载
子类被加载

Process finished with exit code 0

反射

package com.hejin.reflection;

/**
 * @Description 类什么时候会初始化
 * @Author Administrator
 * @Date 2020/12/2 9:51
 */
public class Test06 {

    static {
        System.out.println("Main类被加载");
    }

    public static void main(String[] args) throws ClassNotFoundException {
        /**
         * 2、反射
         */
        Class.forName("com.hejin.reflection.Son");

    }

}

class Father{

    static int b = 2;

    static {
        System.out.println("父类被加载");
    }

}

class Son extends Father {
    static {
        System.out.println("子类被加载");
        m = 300;
    }

    static int m = 100;
    static final int M = 1;
}

结果

Main类被加载
父类被加载
子类被加载

Process finished with exit code 0

被动引用测试

子类引用父类的静态变量

// 子类引用父类的静态变量
System.out.println(Son.b);

结果

Main类被加载
父类被加载
2

Process finished with exit code 0

数组定义类引用

// 数组定义类引用
Son[] array = new Son[5];

结果

Main类被加载

Process finished with exit code 0

引用常量

// 引用常量
System.out.println(Son.M);

结果

Main类被加载
1

Process finished with exit code 0