assylias seems to have found the answer (let me just put it all together):
Chapter "14.21. Unreachable Statements" of the JLS specifies, that, in general, any unreachable statement in the code is considered a compile-time-error, with the only exception being a special treatment of if
-statements to specifically allow for conditional compiles.
Therefore, the only construct that may result in code elimination (if the compiler chooses to do so!) is:
if (compileTimeConstantExpression) {
doThis(); // may be removed if compileTimeConstantExpression == false;
} else {
doThat(); // may be removed if compileTimeConstantExpression == true;
}
(the else
-part is optional, of course)
All other constructs that would allow for code elimination, like for example while (false) ...
, are disallowed and cause a compile-time-error instead rather than resulting in conditional compilation.
The definition for what constitutes an acceptable compileTimeConstantExpression
can be found in chapter "15.28. Constant Expressions" of the JLS. Another great page with further examples can be found here: Compile Time Constants in Java
Note: There is no requirement for a compiler to remove the "unreachable" sections of an if
-stament. javac
seems to do this reliably, but other compilers may not. The only way to know for sure is to check the output via decompilation, for example using javap -c
as suggested by Jon Skeet.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…