我的Java类
private static final String constantString = "Constant";
private static final Integer constantInteger = 5;
public static void main(String[] args) {
String s2 = constantString + "append"; // LINENUMBER 9
Integer i2 = constantInteger + 7; // LINENUMBER 10
}
字节码
LINENUMBER 9 L0
LDC "Constantappend"
ASTORE 1
L1
LINENUMBER 10 L1
GETSTATIC TestClass.constantInteger : Ljava/lang/Integer;
INVOKEVIRTUAL java/lang/Integer.intValue()I
BIPUSH 7
IADD
问题1:为什么编译器不会用5替换final Integer(constantInteger)的值,但对于String却可以!
如果删除Integer变量的final关键字
Java代码:
private static Integer constantInteger = 5;
字节码:
LINENUMBER 10 L1
GETSTATIC TestClass.constantInteger : Ljava/lang/Integer;
INVOKEVIRTUAL java/lang/Integer.intValue()I
BIPUSH 7
两种情况下字节码相同(静态final Integer,静态Integer)
问题2:那么将Integer定义为final有什么用?