".class" way of obtaining Class - does it initialize the class?
class, java
Solution
How about testing it yourself, to see what your VM does?
Just use this class with all three methods (in independent runs, as it will only be initialized once at most!)
class Example {
static {
System.out.println("Class was initialized!");
}
public static int bananas = 0;
}
for details when a class is supposed to be initialized, see http://docs.oracle.com/javase/specs/#12.4.1
Roughly speaking, a class is supposed to be initialized when either
- the first instance is created
- a `static` method is invoked
- a non-final `static` field is used
- some more complex corner cases
So essentially, when you first use anything of the actual class, not just reference it.
But e.g. `Example.bananas = 1;` should also trigger class initialization, without having an instance.
Problem
Question is about Java. There are three ways of obtaining classes of a type (note that code is just a collection of snippets for demonstration): ``` Class c1 = Class.forName("com.mypkg.MyClass"); //assumes initialize = true // - OR - Class c1 = Class.forName("com.mypkg.MyClass", true/false, this.getClass().getClassLoader()); Class c2 = com.mypkg.MyClass.class; // - OR - import com.mypkg.MyClass; Class c2 = MyClass.class; MyClass mc = new MyClass(); Class c3 = mc.getClass(); ``` My question is about initialization. For method 1, I can control whether class is initialized or not using the boolean argument. For method 3, since an object is created, obviously the class is initialized (right?). But what about method 2? Does calling `.class` initialize the class if it has not already been initialized? And how can one programmatically check whether a class is already initialized or not? Summary answer: Please see accepted solution and its comments for full answer. This is just a summary. Calling `.class` does not initialize the class if it has not already been initialized. You can check whether a class is getting initialized by using a static block in the class definition that prints a message. Reason for original question: According to javadoc of `Class.forName`, "A call to forName("X") causes the class named X to be initialized.". Also there are two `Class.forName` methods including one that accepts a boolean parameter called initialize. According to javadoc, "The class is initialized only if the initialize parameter is true and if it has not been initialized earlier."