Java 标签不规则(可能是错误?)

Java label irregularity (possible bug?)

如果我们查看 Java standard §14.7,我们会发现语句可能有标签前缀,例如:

LabeledStatement:

     Identifier : Statement

理论上,标签应该能够标记任何后续语句。因此,例如,相应地编译以下内容:

public class Test {
    public static void main(String[] args) {
    hello:
        return;
    }

}

直觉上,这也编译:

public class Test {
    int i;
    public static void main(String[] args) {
        Test t = new Test();
    label:
        t.i = 2;        
    }
}

但以下编译:

public class Test {
    public static void main(String[] args) {
    oops:
        int k = 3;  
    }
}

即使这样做(注意范围括号):

public class Test {
    public static void main(String[] args) {
    oops:
        {
            int k = 3;
        }
    }
}

所以问题取决于声明是否是声明。根据标准(和online documentation):

In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements. A declaration statement declares a variable.

我在 OSX 和 Windows 的 Java 7 和 8 中都注意到了这种行为。这是错误还是我误解了标准?

表达式

int k = 3; 

是一个local variable declaration statement

标签语句语法中使用的statement

LabeledStatement:

  Identifier : Statement

不包含局部变量声明语句。因此,您不能直接在带标签的语句中使用它们。

局部变量声明语句可以在 blocks 中使用,可以在标记语句中使用。