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?
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With