from Inside the JAVA2 Virtual Machine P 294- 296
在java文件中,指向编译时常量的类的static final 变量, 会被在运行时解析为一个局部的常量值(也就是说编译成字节码时,会把那些在编译时就能确定的static final 变量直接用常量代替)。这对所有的primitive types(就像int ,float等)和java.lang.String都适用。
这些特别的常量机制源自于java语言的两个特点。第一,常量的局部复制 让static final 变量能够被应用到 switch case语句中。tableswitch 和 lookupswitch
是字节码中实现switch逻辑的指令,它们需要在字节码中查找到case值。而这些指令是不支持运行时对变量的解析的。
另外一个动机是对if等判断语句的编译优化。Java支持根据解析判定值为一个编译时常量来简化对判断语句的编译。如下代码:
class AntHill{ static final boolean debug = true ; } class Example{ public static void main(String[] args){ if (AntHill.debug){ System.out.println("Debug is true!"); } } }
因为编译器会对primitive 常量进行特殊处理,进儿对if判断语句进行优化,决定是否包含某段代码。
main方法的字节码如下:
public static main(String[]) : void GETSTATIC System.out : PrintStream LDC "Debug is true!" INVOKEVIRTUAL PrintStream.println(String) : void LINENUMBER 54 L1 RETURN
这里根本没有出现对AntHill类的调用,也就不会链接、初始化AntHill类。
编译器直接在编译时优化了代码,将AntHill.debug转化为对局部常量的访问,并进一步简化了if判断语句。
如果在源代码如下:
class AntHill{ static final boolean debug = fasle ; } class Example{ public static void main(String[] args){ if (AntHill.debug){ System.out.println("Debug is true!"); } } }
main方法字节码为:
public static main(String[]) : void RETURN没有任何其他代码。
同时,我们需要注意,重新编译的时候不能仅仅编译AntHill.class ,而是要编译所有文件!
(笔者感悟:看来要谨慎使用final static 的 primitive 变量!!)