gpt4 book ai didi

java - 为什么在类没有完全加载的情况下构造一个新对象就可以了?

转载 作者:行者123 更新时间:2023-12-01 08:49:19 24 4
gpt4 key购买 nike

public class Test{
static Test test = new Test();
static {
System.out.println("Test class ...");
}
public static void main(String[] args){

}
}

参见上面的代码,当调用 main 时,类 Test 将被加载,并且将构造一个名为 test 的静态实例,具有 Test 类在调用 static Test test = new Test(); 时已加载?如果不是,这样做安全吗?如果加载,当类已加载但未初始化时构造新对象是否安全?

编辑
上面的代码似乎引起了人们对 main 方法的很多关注,但这不是我要问的。

public class App{
public static void main(String[] args) {
new Test();
}
}
class Test{
static Test app = new Test();
static{
System.out.println("Test ");
}
{
System.out.println("constructing a Test object ...");
}
}

这里的代码,我是否在初始化测试类之前构造测试对象?这样做安全吗? @Thirler 的回答是否表明它不安全但可以这样做?

最佳答案

这是允许的,并且大多数时候这都会很好。然而,这将允许您创建一些乍一看似乎很好但会失败的构造。例如下面的循环引用。

public class InitTest {
static InitTest test = new InitTest();

private int count = 0;

public static void main(String[] args) {

}

public InitTest() {
test.count++;
}
}

这里静态对象的构造函数调用自身。由于构造函数还没有完成,对象还没有被赋值(只有完成的对象被赋值)。这将导致 test.count++;

上出现 NullPointerException

请注意,Java 语言规范是安静可读的,chapter 12讨论加载类并指定初始化的顺序(这是我们正在讨论的阶段的正式名称,它初始化所有静态变量)。第 12.4.1 节对此进行了更多讨论(尽管相当模糊)。粗体部分(我的重点)指的是上面的例子和你的问题。

The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.

The fact that initialization code is unrestricted allows examples to be constructed where the value of a class variable can be observed when it still has its initial default value, before its initializing expression is evaluated, but such examples are rare in practice. (Such examples can be also constructed for instance variable initialization (§12.5).) The full power of the Java programming language is available in these initializers; programmers must exercise some care. This power places an extra burden on code generators, but this burden would arise in any case because the Java programming language is concurrent (§12.4.2).

基本上他们说:因为我们希望初始化强大并且不施加太多限制,所以有可能但很少会出现不起作用的情况。

关于java - 为什么在类没有完全加载的情况下构造一个新对象就可以了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42479587/

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