java类中静态块_java – 为什么.class不调用类中的静态块?
这是我有的代码:
public class StupidClass {
static {
System.out.println("Stupid class loaded!");
}
}
和我有的测试,我单独运行。
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 stupidClassClass = StupidClass.class;
System.out.println(stupidClassClass.getSimpleName());
}
}
当我运行测试foo我会看到:
Stupid class loaded!
StupidClass
但是当我运行测试栏时,我看到的是:
StupidClass
报价从this页..
Class objects are constructed automatically by the Java Virtual
Machine as classes are loaded and by calls to the defineClass method
in the class loader.
所以我的理解是,在测试栏,Stupid类加载,否则我会看到一个null我猜?所以Class对象被创建,因为类本身被加载..
现在引用从this页
Static initialization blocks are run when the JVM (class loader – to
be specific) loads StaticClass (which occurs the first time it is
referenced in code).
所以我期待看到“愚蠢的类加载!文本在测试栏中,但我不是。
Each of the classes Candy, Gum, and Cookie has a static clause that is
executed as the class is loaded for the first time.
这是不是很准确的似乎..
我缺少什么?