gpt4 book ai didi

java - 为什么.class 不调用类中的静态 block ?

转载 作者:IT老高 更新时间:2023-10-28 13:51:43 24 4
gpt4 key购买 nike

这是我的代码:

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<StupidClass> stupidClassClass = StupidClass.class;
System.out.println(stupidClassClass.getSimpleName());
}
}

当我运行测试 foo 我会看到:

Stupid class loaded!
StupidClass

但是当我运行测试 bar 时,我看到的只是:

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?所以类对象被创建是因为类本身被加载了..

现在引用 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).

所以我期待看到“加载愚蠢的类!”测试栏中的文本也是如此,但我不是。

同时引用 Thinking in Java

Each of the classes Candy, Gum, and Cookie has a static clause that is executed as the class is loaded for the first time.

这似乎不太准确..

我错过了什么?

最佳答案

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).

上面的引用是完全错误的,但这只是一种非常普遍的误解。

  1. 在加载时未初始化,但在首次引用静态类成员时。这正是由 specification 控制的。 .

  2. 类加载在第一次引用类时不会发生,而是在依赖于实现的点。

  3. 必须加载类的最后时刻是引用该类时,这与引用类成员不同

Class.forName 默认初始化类,但您可以选择调用采用 boolean initialize 并提供 false 的重载.您无需初始化即可加载类。

关于java - 为什么.class 不调用类中的静态 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39504847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com