Java包装类常量池问题

按照最近项目的开发习惯

Posted by if on 2019-01-10

最近刷脉脉的时候看到一道题

大概是这个样子

1
2
3
4
5
6
7
8
9
10
void pass(){
//todo
}
int main(){
int x =123;
printf("%d",x);
pass();
printf("%d/n",x);
return 0;
}

在pass里进行操作,不动函数定义以及main代码,可以让输出的结果返回123456

因为因为C语言中有指针,所以我就弄了一个粗暴的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void pass(){
int i = 0;
int *p = &i;
while(1){
if(*p == 123){
*p = 456;
break;
}
p++
}
}
int main(){
int x =123;
printf("%d",x);
pass();
printf("%d/n",x);
return 0;
}

在地址里去慢慢找,找到123就替换


平©常(U)工®作(D)的时候用java多一点,寻思用java试试

java语法中没有提供指针,但是可以用java的反射去试试解决,而且值类型也有自己的包装类。

然后题就成了这样

1
2
3
4
5
6
7
8
9
public static void pass(){
//todo
}
public static void main(String[] args) {
Integer x = 123;
System.out.printf(x);
pass();
System.out.println(x);
}

接着去瞅瞅Integer源码

1
2
3
4
5
6
7
8
9
10
11
12
public final class Integer extends Number implements Comparable<Integer> {      
//... 其他代码省略

/**
* The value of the {@code Integer}.
*
* @serial
*/
private final int value;

// ... 其他代码省略
}

发现Integer里有一个这个字段。

然后反射可以读取类中的私有字段,所以就有了解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void pass() throws Exception {
//读取value
Field field = Integer.class.getDeclaredField("value");
//设置为可操作
field.setAccessible(true);
//把123改为456
field.setInt(123, 456);
}
public static void main(String[] args) throws Exception {
Integer x = 123;
System.out.printf(x);
pass();
System.out.println(x);
}

然后去测试了一下


这道题没有问题


因为经常刷题,所有觉得一个测试用例是不够的

当我把题目中的123换为1234 的时候。

果然,这个pass()失效了

一直在撸代码很少看底层写的实现,所有又回去看了看源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];

static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);

// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}

private IntegerCache() {}
}

/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

在查了查资料发现

刚才思考的有点问题,我是直接赋值的并没有调用构造函数,应该有自动装箱操作。

在JDK5.0之前是不允许直接将基本数据类型的数据直接赋值给其对应地包装类的,如:Integer i = 5;

但是在JDK5.0中支持这种写法,因为编译器会自动将上面的代码转换成如下代码:Integer i=Integer.valueOf(5);

这就是Java的装箱.JDK5.0也提供了自动拆箱. Integer i =5; int j = i;

而且cache[]在IntegerCache类中是静态数组,static{......}部分

所以,如果Integer对象初始化时是-128~127的范围,就不需要再重新定义申请空间,直接引用IntegerCache.cache

所以刚才当我把123改为456的时候,其实是把常量池中的123改为了456,而i1引用了常量池中的地址,所以再次输出的时候,输出了456

1
2
3
4
5
6
7
8
Integer i1 = 1;
Integer i2 = 1;
System.out.println(i1 == i2);
//true
i1 = 1000;
i2 = 1000;
System.out.println(i1 == i2);
//false

1231234的时候超过了128,就不是从常量池中去的数据,所以在不操作对象本身的情况下4,无法修改其值(我试了好多种办法)。

java中基本类型的包装类的大部分都实现了常量池技术,这些类是Byte,Short,Integer,Long,Character,Boolean,另外两种浮点数类型的包装类则没有实现。另外Byte,Short,Integer,Long,Character这5种整型的包装类也只是在对应值小于等于127时才可使用对象池,也即对象不负责创建和管理大于127的这些类的对象。

以上