gpt4 book ai didi

java - Java 中的编译器如何决定无法访问的代码?

转载 作者:行者123 更新时间:2023-12-01 22:33:37 27 4
gpt4 key购买 nike

编译器如何决定无法访问的代码?

考虑这些

public class Test15 {

public static final boolean verdict = false;
public static final int verdictInt = 2;

public static void main(String[] args) throws IOException {

// case1
if (verdict) {
System.out.println(1);
} else {
System.out.println(2);
}// compiles

//case 2
int val = 5;
switch (val) {
case verdictInt:System.out.println(3);
break;
}// compiles

//case 3
while (false) {

}// does not compile

//case 4
return 6;
return 7;
//does not compile

}
}

因此,当编译器确定代码无法访问时。是否是因为(缺乏更好的术语)硬代码(如情况 4)。因为据我所知, verdict、verdictInt 也符合编译时常量的条件并且依也。根据我的阅读,能够使用常量 verdictInt 作为 switch case 标签表明它是一个编译时间常量。

如果我的推理存在任何基本缺陷,请告诉我。

最佳答案

Java Language Specification关于无法访问的代码的部分很好,但读起来很长。我会将其浓缩为您的问题的翻译内容。

情况1:

verdict 可以被视为一个标志变量;它可能会也可能不会用于调试目的。如果是这样,那么破坏编译将导致重大设计目标的失败。规范明确指出了这一点:

The rationale for this differing treatment [with if as opposed to while] is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

情况2:

您的 switch 语句可以按照 JLS 的规则正常完成:

A switch statement can complete normally iff at least one of the following is true:

  • The switch block is empty or contains only switch labels.
  • The last statement in the switch block can complete normally.
  • There is at least one switch label after the last switch block statement group.
  • The switch block does not contain a default label.
  • There is a reachable break statement that exits the switch statement.

您的switch没有default标签,因此您的switch可以正常完成。它只是从开关中掉出来。

情况3:

这明确地编译。案例 1 引起了一些注意,但这里已经详细说明了,强调我的:

A while statement can complete normally iff at least one of the following is true:

  • The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.

  • There is a reachable break statement that exits the while statement.

The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.

条件表达式为false,因此根据定义,您无法访问所包含的语句。

情况 4:

return 是一种特殊情况;它completes abruptly 。一旦语句突然完成,根据定义,该语句之后的任何语句都将无法访问。

关于java - Java 中的编译器如何决定无法访问的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27206124/

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