/**
* Created by liuzhilei on 2017/2/13.
*/
public class StaticTest {
/**
* static会放到方法去,但是不是常量池。常量池在方法区中
*/
private static int i = 1 ;
/**
* final修饰的对象,即便是基本数据类型的包装类,
* 都不会放到常量池,因为final修饰的是对象的引用,
* 只要对象的地址不发生变化,对象本身通过get,set发生变化还是可以的,所以不可能放到常量池
*/
private final Integer integer = 2 ;
/**
* 常量池中只是保存了对a的变量引用
*/
private int a = 3 ;
//final修饰的基本数据类型,因为已经不可变,所以会放到常量池中
private final int finalA = 4 ;
//String类型的变量本身就是不可变的,所以肯定会放到常量池中
private String str = "liuzhilei" ;
}
利用java命令即可分析出来:javap -v StaticTest.class,下面截取的是常量池数据。
Constant pool:
#1 = Methodref #10.#31 // java/lang/Object."<init>":()V
#2 = Methodref #32.#33 // java/lang/Integer.valueOf:(I)Ljava
/lang/Integer;
#3 = Fieldref #9.#34 // com/liu/j2setest/constantspool/Sta
ticTest.integer:Ljava/lang/Integer;
#4 = Fieldref #9.#35 // com/liu/j2setest/constantspool/Sta
ticTest.a:I
#5 = Fieldref #9.#36 // com/liu/j2setest/constantspool/Sta
ticTest.finalA:I
#6 = String #37 // liuzhilei
#7 = Fieldref #9.#38 // com/liu/j2setest/constantspool/Sta
ticTest.str:Ljava/lang/String;
#8 = Fieldref #9.#39 // com/liu/j2setest/constantspool/Sta
ticTest.i:I
#9 = Class #40 // com/liu/j2setest/constantspool/Sta
ticTest
#10 = Class #41 // java/lang/Object
#11 = Utf8 i //static修饰变量,保存到了方法区,没有存放到常量池,常量池存放i的引用
#12 = Utf8 I
#13 = Utf8 integer //final修饰的对象,不会保存到常量池,存放integer的引用
#14 = Utf8 Ljava/lang/Integer;
#15 = Utf8 a //普通变量,常量池保存了对变量a的引用
#16 = Utf8 finalA
#17 = Utf8 ConstantValue
#18 = Integer 4 //final修饰的基本数据类型,值保存到了常量池中
#19 = Utf8 str
#20 = Utf8 Ljava/lang/String;
#21 = Utf8 <init>
#22 = Utf8 ()V
#23 = Utf8 Code
#24 = Utf8 LineNumberTable
#25 = Utf8 LocalVariableTable
#26 = Utf8 this
#27 = Utf8 Lcom/liu/j2setest/constantspool/StaticTest;
#28 = Utf8 <clinit>
#29 = Utf8 SourceFile
#30 = Utf8 StaticTest.java
#31 = NameAndType #21:#22 // "<init>":()V
#32 = Class #42 // java/lang/Integer
#33 = NameAndType #43:#44 // valueOf:(I)Ljava/lang/Integer;
#34 = NameAndType #13:#14 // integer:Ljava/lang/Integer;
#35 = NameAndType #15:#12 // a:I
#36 = NameAndType #16:#12 // finalA:I
#37 = Utf8 liuzhilei //String类型本身就是final,所以会保存到常量池
#38 = NameAndType #19:#20 // str:Ljava/lang/String;
#39 = NameAndType #11:#12 // i:I
#40 = Utf8 com/liu/j2setest/constantspool/StaticTest
#41 = Utf8 java/lang/Object
#42 = Utf8 java/lang/Integer
#43 = Utf8 valueOf
#44 = Utf8 (I)Ljava/lang/Integer;