package integerReflect;
import java.lang.reflect.Field;
public class IntegerCache {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class cache = Integer.class.getDeclaredClasses()[0];
Field myCache = cache.getDeclaredField("cache");
myCache.setAccessible(true);
Integer[] newCache = (Integer[]) myCache.get(cache);
newCache[129] = newCache[128];
Integer a = 1;
int b = a + a;
int c = a + 10;
System.out.println(a + " + " + a + " = " + b);
System.out.println(a + " + 10 = " + c);
}
}
- List item
先上代码,运行结果:
以上示例中,a=1 是明码标价的,为何打印的时候,a就变成了0?
这里要说到 Integer 的缓存机制,在 Integer 的缓存机制里,存在 [-128,127]的数,当我们直接定义 Integer 值的时候,如果这个值在此范围内,Integer 会自行到它的缓存中去取用,反之才新建 Integer 对象。
在 Integer 的缓存机制中,
cache[0] == -128,
cache[1] == -127,
cache[2] == -126,
……
依次类推。
当我们在上面的实例中通过反射获取到缓存的cache数组之后,将cache[128]的值赋给cache[129],意思就是说将0的值赋给1,
当我们使用 Integer a = 1 声明a的值的时候,其实a是到缓存机制中取到了cache[129]的值,即0,所以后面才会将a的值识别程0,是不是很神奇啊
—— 本文的部分代码参考了微信公众号“Java后端技术”