Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are imported classes loaded in java?

In the following scenario ,

import A;
public class B{
    static A a;
    static{
        a = new A();
    }
}

Is it possible that the static initialization block gets called before a is properly initialized? Note: A here is a logging framework.

like image 779
nikel Avatar asked Dec 27 '22 04:12

nikel


2 Answers

In the case you mention above static block will be called before A is initialized as static block will be called when class loads (Class B in your case). So when you do

B.someStaticMethod() 

First class B will be loaded where static block is called with it(One time process in JVM) and then static method will be called.

Also Note that Importing statement to load the class does not load the class. It happens when yo do some operation on that class.

like image 171
M Sach Avatar answered Jan 09 '23 03:01

M Sach


Imports have nothing to do with it. There are no imports at runtime.

Referenced classes are loaded during the linking phase, which precedes the initialization phase. In this case A is loaded during the link resolution step for B, before B's static initializer executes.

Reference: JVM Specification: Loading, Linking, and Initializing.

like image 44
user207421 Avatar answered Jan 09 '23 01:01

user207421