简体   繁体   English

Java静态初始化块上的奇怪代码

[英]Strange code on Java Static Initialization Blocks

When going through the JLS 8.3.2.3 I wasn't able to understand the following code. 通过JLS 8.3.2.3时,我无法理解以下代码。

class Z {
static { i = j + 2; }
static int i, j;
static { j = 4; }
}

The code is resulting in the error Cannot reference a field before it is defined 代码导致错误Cannot reference a field before it is defined

But if I change the code to 但是,如果我将代码更改为

class Z {
static { i = 2; }
static int i, j;
static { j = 4; }
}

The code is getting compiled. 代码正在编译中。 But in both the cases the variable definition is after the initialization block. 但在这两种情况下,变量定义都在初始化块之后。 What is the mystery behind this? 这背后的秘密是什么?

You can assign to a value earlier than its declaration - you just can't read it. 您可以在声明之前分配一个值 - 您无法读取它。 So this fails too: 所以这也失败了:

static { System.out.println(j + 2); }
static int j;

Whereas this is fine: 这很好:

static { j = 5; }
static int j;

One of the four conditions in section 8.3.2.3 for an invalid usage is: 第8.3.2.3节中无效使用的四个条件之一是:

  • The usage is not on the left hand side of an assignment. 用法不在作业的左侧。

(The double-negatives in that section are making my head hurt, but I think it relevant!) (该部分的双重否定让我头痛,但我觉得这很重要!)

To be honest, that part of the spec is one of the worst I've seen - it's really unclear. 说实话,这部分规格是我见过的最糟糕的一部分 - 它真的不清楚。 But the upshot is that you can assign but not read :) 但结果是你可以分配但不读:)

Actually,Its an compiler basics, 实际上,它是一个编译基础,

the assignment statements are executed from right to left. 赋值语句从右到左执行

eg i=2; 例如i=2;

it means 2 is assigned to i,and 2 is constant hence no need to declare it 它表示2分配给i,2表示常量,因此无需声明它

In the other hand if we write 另一方面,如果我们写

i=j+2;

it will compile j first and then assign it to the i hence it causes the error because j is not defined yet. 它将首先编译j,然后将其分配给i,因此它会导致错误,因为j尚未定义。

In i = j + 2; i = j + 2; you use the variable j that is initialize in a different static block. 您使用在不同静态块中初始化的变量j

You should put everything togheter, in only one static block, the j initialization and the expression to get the code compiled. 您应该只在一个静态块中放置所有内容, j初始化和表达式以获取编译的代码。 This code works: 此代码有效:

public class Z {

    static int i, j;
    static { j = 4; 
            i = j + 2; }

}

Davide 达维德

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM