深入Java虚拟机: 2 + 2 = 5 ?

技巧应在于对cache的修改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Why100equalAnd1000notEqual
{
public static void main(String args[]) throws NoSuchFieldException,Exception {
Class cache=Integer.class.getDeclaredClasses()[0];
Field myCache=cache.getDeclaredField("cache");
myCache.setAccessible(true);
Integer newCache[]=(Integer[]) myCache.get(cache);
newCache[132]=newCache[133];
int a=2;
int b=a+a;
System.out.printf("%d + %d = %d \n",a,a,b);
}
}