I have this code (put aside its appropriateness for now):
Class<?> cacheClass = Class.forName("java.lang.Integer$IntegerCache");
Field cacheField = cacheClass.getDeclaredField("cache");
cacheField.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(cacheField, cacheField.getModifiers() & ~Modifier.FINAL);
Integer betterCache[] = new Integer[255];
for (int i = 0; i < betterCache.length; i++) {
betterCache[i] = 20;
}
cacheField.set(null, betterCache);
System.out.println(10);
System.out.println((Integer) 10);
I expect the second println to print 20, as I replaced cached Integers with 20. When I debug program in Eclipse it does as I expect, it gets the value from the cache and prints 20, whereas it prints 10 in both cases when I just run it either from IDE or by invoking java. How can this behavior be explained?
UPD: It works this way if compiled with 1.8 javac. It prints 10 and 20 if compiled with 1.6 version.
Integer.valueOfmethod to print it, and in that method it takes values from the cache I just substituted with an array filled with 20.