gpt4 book ai didi

java - 如果放置在声明之前,则静态初始化程序错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:26:01 26 4
gpt4 key购买 nike

我注意到静态初始化器中的某些东西可能是 javac 中的错误。我构建了一个场景,我可以在其中为变量赋值但不读回该值。

下面是两个示例,第一个编译正常,第二个在尝试从 tmp 读取值时出错,但出于某种原因允许将值分配给 tmp。我可以理解它是否既不能读取也不能写入变量,因为 tmp 是在静态初始化程序之后声明的,但是只有其中一个错误对我来说没有意义。

//Compiles Successfully:
public class Script
{
public static Object tmp;
static
{
tmp = new Object();
System.out.println(tmp);
}

}

//error only on the read but not the assignment
public class Script
{

static
{
tmp = new Object();
System.out.println(tmp);
}
public static Object tmp;
}

进一步强调这一点,这确实编译成功。

public class Script
{

static
{
tmp = new Object();
}
public static Object tmp;
}

最佳答案

这似乎是在规范中定义的(参见 JLS 8.3.2.3 ):

The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

  • The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer
    of C.

  • The usage is not on the left hand side of an assignment.

  • The usage is via a simple name.

  • C is the innermost class or interface enclosing the usage.

因此,如果用法在赋值的左侧,那么它是合法的,因为第二个不再成立。

关于java - 如果放置在声明之前,则静态初始化程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16420954/

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