java - 当我添加 "this"时,递归初始化程序有效吗?

标签 java

正如预期的那样,这无法编译(出现 illegal forward reference 错误):

class test {
    int x = x + 42;
}

但这有效:

class test {
    int x = this.x + 42;
}

发生了什么事?在后一种情况下分配了什么?

最佳答案

在 x 的初始化过程中发现和禁止对 x 的所有访问太难了。例如

int x = that().x;                |    int x = getX();
                                 |
Test that(){ return this; }      |    int getX(){ return x; }

规范停留在“通过简单名称访问”,并没有尝试更全面。

在另一部分“明确分配”中,规范做了类似的事情。例如

public class Test
{
    static final int y;
    static final int z = y;  // fail, y is not definitely assigned 
    static{ y = 1; }
}

public class Test
{
    static final int y;
    static final int z = Test.y;  // pass... because it's not a simple name
    static{ y = 1; }
}

有趣的是,“定义赋值”特别提到 this.x 等价于 x

(or, for a field, the simple name of the field qualified by this)

这个子句也可以添加到 NPE 引用的部分。

  • the usage is via a simple name (or a simple name qualified by this)

但最后,不可能在编译时分析所有可能的使用/访问一个字段。

关于java - 当我添加 "this"时,递归初始化程序有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820302/

相关文章:

java - JPanel 的精确副本或撤消..建议

java - 提供连接的 OutputStream 和 InputStream 的最佳实践

java - 使用 JSch 的多个命令

java - 通过电子邮件发送文件 - 无法获取附件 - Android

java - 如何使用 SpringBoot Security 禁用 OPTIONS 的基本 http 身份验证

java - 如何为spring配置web.xml

java - 从已编译的类中推断出公开可用的 Java 代码的版本

java - 使用 Install4J 创建的 MacOSX 安装程序与标准应用程序包不同

java - 如何使用 String.format()

java - 算法运行时间分析