Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

When is the time to load the Java class

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "when is the time to load the Java class", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "when is the time to load the Java class"?

Four situations that must be initialized

There are four case classes that must be initialized, for which the original description is as follows:

However, for the initialization phase, the virtual machine specification strictly stipulates that there are and only four cases that the class must be initialized immediately, and loading, verification, and preparation naturally need to start before that.

1: when you encounter four bytecode instructions such as new, getstatic, putstatic or invokestatic, if the class has not been initialized, you need to trigger its initialization first. The most common java code scenarios for generating these four instructions are when an object is instantiated with the new keyword, when a static field of a class is read or set (except for a static field that is decorated by final, and the result has been put into a constant pool at compile time), and when a class's static method is called.

2: when you make a reflection call to a class using the method of the java.lang.reflect package, if the class has not been initialized, you need to trigger its initialization first.

3: when initializing a class, if you find that its parent class has not been initialized, you need to trigger the initialization of its parent class first.

4: when the virtual machine starts, the user needs to specify a main class to execute (the class that contains the main () method), and the virtual machine initializes the main class first.

The above four points are verified by code one by one. In the first point, we talk about four initialization scenarios, which are:

① instantiates objects with the new keyword

② read class static fields

③ sets the static field of the class

④ calls the static method of a class

Before verification, we need to reach a consensus: the virtual machine performs the operations in the static statement block when initializing the class, so we can determine whether the class is loaded based on whether the code in the static statement block is executed or not. To do this, I created a SubClass class

Package com.test.jvm.classloading;/** * @ author fc * / public class SubClass {static {System.out.println (subclass initialization);} public static int a = 10; public static int getA () {return a;}}

Execute (one at a time) the following four pieces of code in the main method to simulate the above four scenarios

Package com.test.jvm.classloading;/** * @ author fc * / public class Main {public static void main (String [] args) {SubClass subClass = new SubClass (); System.out.println (SubClass.a); SubClass.getA (); SubClass.a = 30;}}

As expected, the output contains "subclass initialization", indicating that the above four ways can indeed trigger class initialization.

Next, let's look at the second point. A reflection call to a class triggers the initialization of the class.

Package com.test.jvm.classloading;/** * @ author fc * / public class Main {public static void main (String [] args) throws ClassNotFoundException {Class.forName ("com.test.jvm.classloading.SubClass");}}

The above reflection call also outputs "subclass initialization" normally.

Third, if the parent class is not initialized, initialize the parent class first, then create a parent class, and let the previous subclass inherit the parent class

Package com.test.jvm.classloading;/** * @ author fc * / public class SuperClass {static {System.out.println (parent initialization);} public static int b = 20;} package com.test.jvm.classloading;/** * @ author fc * / public class SubClass extends SuperClass {static {System.out.println (subclass initialization);} public static int a = 10 Public static int getA () {return a;}}

When we execute any of the test statements in the above main method again, we find that "parent class initialization" is output before the original output "subclass initialization", indicating two points: the ① parent class will also initialize, and the ② parent class will initialize before the subclass.

Fourth, the virtual machine first initializes the main class that contains the main method, and then we add a static code block to the main class

Package com.test.jvm.classloading;/** * @ author fc * / public class Main {static {System.out.println ("initialize main class");} public static void main (String [] args) throws ClassNotFoundException {SubClass subClass = new SubClass ();}}

You can see that the output results are as follows, which fully confirms the fourth point.

Do not initialize actively

For cases that will not initialize actively, there are also the following situations in the book.

The first is that calling the parent static code (including static methods and static variables) through the subclass name will not be initialized, which is also explained by the code below.

Package com.test.jvm.classloading;/** * @ author fc * / public class Main {public static void main (String [] args) throws ClassNotFoundException {System.out.println (SubClass.b);}}

The output is as follows, and you can see that only the parent class is initialized without initializing the subclass.

The second is that creating an object through an array does not trigger this class's initialization.

Package com.test.jvm.classloading;/** * @ author fc * / public class Main {public static void main (String [] args) throws ClassNotFoundException {SuperClass [] supers = new SuperClass [10];}}

The output is empty.

The third is that calling the constant modified by final does not trigger the initialization of the class, so I add a constant to the parent class.

Package com.test.jvm.classloading;/** * @ author fc * / public class SuperClass {static {System.out.println (parent initialization);} public static int b = 20; public final static String STATE = "constant";} package com.test.jvm.classloading;/** * @ author fc * / public class Main {public static void main (String [] args) {System.out.println (SuperClass.STATE);}

You can see that the output simply prints the value of the constant and does not initialize the class.

Supplement

So far, the loading timing of the classes described in the book has been illustrated with examples, and then an example seen in the blogger Boblim is shown.

/ * * @ author fc * / class SingleTon {private static SingleTon singleTon = new SingleTon (); public static int count1; public static int count2 = 0; private SingleTon () {count1++; count2++;} public static SingleTon getInstance () {return singleTon;}} public class Test {public static void main (String [] args) {SingleTon.getInstance () System.out.println ("count1=" + SingleTon.count1); System.out.println ("count2=" + SingleTon.count2);}}

Output count1=1,count2=0, as to why this result is output has been explained in detail in the linked blog, and the output also supports the following sentence.

The class constructor () method is generated by the compiler automatically collecting the assignment actions of all class variables in the class and the statements in the static statement block (static block). The order in which the compiler collects is determined by the order in which the statements appear in the source file.

It is the class variables that are assigned in order, so the above count2 will be re-assigned to 0, resulting in this output.

At this point, I believe that you have a deeper understanding of "when is the time to load the Java class?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report