Java编译器:停止抱怨死代码 [英] Java Compiler: Stop complaining about dead code

查看:138
本文介绍了Java编译器:停止抱怨死代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于测试目的,我经常在已经存在的项目中开始输入一些代码。所以,我想测试的代码在所有其他代码之前,像这样:

For testing purposes, I often start typing some code in an already existing project. So, my code I want to test comes before all the other code, like this:

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...
}

但是编译器抱怨有关 return -statement,因为下面的死代码。 (在C ++中,编译器服从程序员,只是编译返回语句)

But the compiler complains about the return-statement, because of the following "dead code". (While in C++ the compiler obeys the programmer and simply compiles the return statement)

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

To prevent the compiler complains, I write a stupid if-statement:

if (0 != 1) return;

我讨厌它。为什么编译器不能做我要求的?是否有一些编译标志或注释或任何解决我的问题?

I hate it. Why can't the compiler do what I ask? Are there some compilation flags or annotations or whatever to solve my problem?

感谢

推荐答案

这个行为没有标志。使死代码成为编译时错误的规则是

There are no flags to turn of this behaviour. The rules that make dead code a compile time error are part of the JLS (§14.20 Unreachable Statements) and can't be turned off.

循环中有一个明显的漏洞,允许这样的代码:

There's an explicit loophole in the loop which allows code like this:

if (true) return;

someOtherCode(); // this code will never execute, but the compiler will still allow it

显式地允许注释或条件编译(取决于一些 static final boolean 标志)。

如果你好奇:漏洞是基于这样的事实: if 语句的条件表达式的已知常数值不是在检查如果语句中或之后的代码的可达性时考虑。类似的情况发生在,其中已知常数值 被考虑,因此此代码不会编译:

In case you're curious: the loophole is based on the fact that a known-constant value of the condition expression of an if statement is not considered when checking reachability of code within or after the if statement. A similar situation occurs with while, where known-constant values are considered, so this code will not compile:

while (true) return;

someOtherCode(); // this will be flagged as an unreachable statement

这篇关于Java编译器:停止抱怨死代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆