Java编译器:停止抱怨死代码

Mar*_*aux 8 java compiler-construction return dead-code

出于测试目的,我经常开始在现有项目中键入一些代码.所以,我想要测试的代码出现在所有其他代码之前,如下所示:

public static void main(String[] args)
{
    char a = '%';
    System.out.println((int)a);
    // To know where '%' is located in the ASCII table.

    // But, of course, I don't want to start the whole project, so:
    return;

    // The real project starts here...
}
Run Code Online (Sandbox Code Playgroud)

但编译器抱怨return-statement,因为下面的"死代码".(在C++中,编译器服从程序员并简单地编译return语句)

为了防止编译器抱怨,我写了一个愚蠢的if陈述:

if (0 != 1) return;
Run Code Online (Sandbox Code Playgroud)

我讨厌它.为什么编译器不能按我要求做?是否有一些编译标志或注释或其他什么来解决我的问题?

谢谢

Joa*_*uer 10

没有标志可以改变这种行为.使死代码成为编译时错误的规则是JLS(§14.21无法访问的语句)的一部分,无法关闭.

循环中存在明显的漏洞,允许这样的代码:

if (true) return;

someOtherCode(); // this code will never execute, but the compiler will still allow it
Run Code Online (Sandbox Code Playgroud)

这是明确地允许"注释"或条件编译(取决于某些static final boolean标志).

如果你很好奇:漏洞是基于这样一个事实:当在语句内或语句之后检查代码的可达性时,考虑if语句的条件表达式的已知常量值.考虑已知常量值的情况下会出现类似情况,因此此代码将无法编译:ifwhile

while (true) return;

someOtherCode(); // this will be flagged as an unreachable statement
Run Code Online (Sandbox Code Playgroud)