DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Reflection - Integer Destroyer
import java.lang.reflect.Field;
public class IntDestroyer {
/**
* @param args
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws SecurityException,
NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field value = Integer.class.getDeclaredField("value");
value.setAccessible(true);
value.set(1, 2);
System.out.println(Integer.valueOf(1));
System.out.printf("5-4 => %d%n",5-4);
value.set(1001, 1002);
System.out.println(Integer.valueOf(1001));
}
}
<b>Program Output:</b>
2
5-4 => 2
1001
The statement 'value.set(1, 2)' changes the internal cache value '1' to '2'. Note that this cache applies only for the values in the range -128 thru 127 (inclusive). Values beyond this range are not cached. For instance, the value 1001 was not cached and hence the statement 'value.set(1001, 1002)' didn't modify the value 1001.
<b>Reference</b>:
* http://blogs.sun.com/darcy/entry/boxing_and_caches_integer_valueof
* http://www.javaspecialists.eu/talks/oslo09/ReflectionMadness.pdf





