1 package com.noway.test;
2
3 import java.lang.reflect.Field;
4
5 /**
6 * Integer的内部类IntegerCache作用
7 * @author Noway
8 *
9 */
10 public class TestIntegerCache {
11 public static void main(String[] args) throws Exception {
12 int a = 10;
13 int b = 20;
14 cache();
15 change(a, b);
16 System.out.println("a========="+Integer.valueOf(a)); // 100
17 System.out.println("b========="+Integer.valueOf(b)); // 200
18 }
19
20 /**
21 * Integer中-128到127之间的值已经提前缓存(该段值是常用值,以便减少内存开销),使用==两个对象依然是相等的
22 */
23 static void cache(){
24 Integer it1 = 10;
25 Integer it2 = 10;
26 System.out.println(it1==it2);//true
27 Integer it3 = 900;
28 Integer it4 = 900;
29 System.out.println(it3==it4);//false
30 }
31
32 /**
33 * i[128+a]这样写的原因: 数组的索引从0开始,但cache第一个值是-128,为了将索引的值等于索引(即cache[i]=i),所以使用i[128+a]的方式
34 * 此处也可查看源码Integer.valueOf()方法
35 * @param a
36 * @param b
37 * @throws Exception
38 */
39 static void change(int a, int b) throws Exception{
40 Class<?> clz = Integer.class.getDeclaredClasses()[0];//获取Integer类的内部类IntegerCache
41 Field field = clz.getDeclaredField("cache");//获取内部类的属性cache
42 field.setAccessible(true);
43 Integer[] i = (Integer[]) field.get(clz);//获取属性cache的值
44 i[128+a] = 100;//将缓存cache中索引为128+a的值变为100;即原本值为10,现在值变成了100。
45 i[128+b] = 200;//同上
46 }
47
48 }