This is the code I have:
public class StupidClass { static { System.out.println("Stupid class loaded!"); } }
And the tests that I have that I run separately .
import org.junit.Test; public class StupidTest { @Test public void foo() throws ClassNotFoundException { final Class<?> stupidClass = Class.forName("StupidClass"); System.out.println(stupidClass.getSimpleName()); } @Test public void bar() throws ClassNotFoundException { final Class<StupidClass> stupidClassClass = StupidClass.class; System.out.println(stupidClassClass.getSimpleName()); } }
When I run the foo test, I will see:
Stupid class loaded! StupidClass
But when I run the bar test, I see the following:
StupidClass
Quote from this page .
Class objects are automatically created by the Java Virtual Virtual Machine. The machine boots as classes and calls to the defineClass method in the class loader.
So, I understand that the Stupid class is loaded in the test panel, otherwise I would see zero, I think? Thus, the class object is created because the class itself is loading.
And now, linking to this page
Static initialization blocks are triggered when the JVM (class loader - be specific) loads StaticClass (which is the first time a link to the code occurs).
So, I expect to see the "Stupid class loaded!" text in the test panel, but I do not know.
Also cited Thinking in Java
Each of the Candy, Gum, and Cookie classes has a static clause that runs when the class first loads.
which is not very accurate, it seems.
What am I missing?
java initialization static class
Koray Tugay Sep 15 '16 at 7:00 2016-09-15 07:00
source share