出于测试目的,我经常开始在现有项目中输入一些代码。因此,我想要测试的代码位于所有其他代码之前,如下所示:
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
-声明,因为以下“死代码”。 (而在C++中,编译器服从程序员并简单地编译return语句)
为了防止编译器抱怨,我写了一个愚蠢的if
-陈述:
if (0 != 1) return;
我恨它。为什么编译器不能按照我的要求做?是否有一些编译标志或注释或其他内容可以解决我的问题?
Thanks
没有任何标志可以关闭此行为。使死代码成为编译时错误的规则是JLS 的一部分(§14.21 无法访问的语句) https://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#236365并且无法关闭。
循环中有一个明显的漏洞,允许这样的代码:
if (true) return;
someOtherCode(); // this code will never execute, but the compiler will still allow it
这个做完了明确地允许“注释掉”或条件编译(取决于某些static final boolean
flag).
如果您好奇:该漏洞基于以下事实:if
声明是not检查代码之内或之后的可达性时考虑if
陈述。类似的情况也发生在while
,其中已知常数值are考虑到,所以这段代码将无法编译:
while (true) return;
someOtherCode(); // this will be flagged as an unreachable statement
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)