Reflection - Integer Destroyer
Join the DZone community and get the full member experience.
Join For Free
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));
}
}
Program Output:
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.
Reference:
* http://blogs.sun.com/darcy/entry/boxing_and_caches_integer_valueof
* http://www.javaspecialists.eu/talks/oslo09/ReflectionMadness.pdf
Data Types
Opinions expressed by DZone contributors are their own.
Comments