1. Active reference of the class will definitely cause initialization of the class. When the virtual machine starts, first initialize the class where the main method is located
Instantiate an object of a class
Call the static members of the class (except final constants) and static methods
Use the method of the java.lang.reflect package to make a reflection call to the class
When initializing a class, if its parent class has not been initialized, its parent class will be initialized first
2. Passive reference of the class, no initialization of the class will occur
When accessing a static field, only the class that actually declares this field will be initialized. For example: when a static variable of a parent class is referenced through a subclass, it will not cause the subclass to be initialized
Defining a class reference through an array will not trigger the initialization of this class
Reference constants will not trigger this Initialization of the class (constants are stored in the constant pool of the calling class during the link phase)
Example
package com.volcano.reflection; //什么时候会发生类的初始化,除了第一个注释一直开着,其他都要独立打开测试,否则不准确 public class TestReflection3 { static { //1.虚拟机启动就会最先初始化main方法所在的类 会 System.out.println("main方法被加载"); } public static void main(String[] args) throws ClassNotFoundException { //2.实例化一个对象 会 //new Father(); //3.调用类的静态成员(除了final常量)和静态方法 会 //System.out.println(Son.a); //4.使用java.lang.reflect包的方法对类进行反射调用 会 //Class cls = Class.forName("com.volcano.reflection.Father"); //5.当初始化一个类,如果其父类没有被初始化,则先会初始化它的父类 会 //new Son(); //6.当访问一个静态域时,只有真正声明这个域的类才会被初始化 不会 //System.out.println(Father.a);//两个都是只加载Father //System.out.println(Son.a);//因为a是Father的静态成员 //7.通过数组定义类引用,不会触发此类的初始化 不会 //Father[] fathers = new Father[10]; //8.引用常量不会触发此类的初始化 不会 //System.out.println(Father.B); } } class Father{ static { System.out.println("Father被加载"); } static int a=100; static final int B = 300; } class Son extends Father{ static { System.out.println("Son被加载"); } static int c=200; }
The above is the detailed content of Rewrite: What are the ways to reference Java classes?. For more information, please follow other related articles on the PHP Chinese website!