Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who invokes the class initializer method <clinit> and when?

Tags:

java

jvm

bytecode

I know that the new, dup, invokespecial and astore bytecode pattern will invoke the instance initializer method <init> when someone instance a Java class from the Java language point of view, but i never figure out who invoke the special <clinit>method and when does this happen?

My guess is that <clinit> is invoked before <init> method. Can any body give me some information to prove it? Is this documented in the JVM Specification or Java Language Specification?

like image 359
George Avatar asked Apr 10 '13 07:04

George


1 Answers

<clinit> is a static method added by javac and called by JVM after class loading. We can see this method in class bytecode with bytecode outline tools. Note that <clinit> is added only if a class needs static initilization, e.g

public class Test1 {
    static int x  = 1; 

    public static void main(String[] args) throws Exception {
    }
}

public class Test2 {
    static final int x  = 1; 

    public static void main(String[] args) throws Exception {
    }
}

Test1 has <clinit> because its field x needs to be initialized with 1; while Test2 has no <clinit> method because its x is a constant.

It's also interesting to note that Class.forName has boolen intialize param which determines if the class should be initialized after loading or not.

like image 87
Evgeniy Dorofeev Avatar answered Sep 22 '22 13:09

Evgeniy Dorofeev