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

Snippets has posted 5883 posts at DZone. View Full User Profile

2 + 2 = 5

03.14.2007
| 2709 views |
  • submit to reddit
        Here is some very exciting Java code for printing 5.

import java.security.*;
import java.lang.reflect.*;
import java.util.*;

public class Test
{
    public static void main(String[] args) throws Exception
    {   
        AccessController.doPrivileged( new PrivilegedAction<Object>(){ public Object run(){try {
        Field field = Class.forName("java.lang.Integer$IntegerCache").getDeclaredFields()[0];
        field.setAccessible(true);

        Integer[] cache = (Integer[])field.get(null);
            
        cache[130] = 3;  
            
        Integer foo = 2;
 
        System.out.println(foo + 2); 
            
        return null;} catch(Exception e) { throw new RuntimeException(e); } } }); 
    }


}

    

Comments

Snippets Manager replied on Wed, 2007/02/14 - 2:44pm

How this works is as follows: Integer maintains an internal cache of Integer objects for values from -128 to 127. This is stored on the inner class IntegerClass (this is what the Class.forName("java.lang.Integer$IntegerCache") line fetches) as an array. When you do Integer.valueOf(int) it will fetch an object from this cache rather than construct a new one if it is within the appropriate range. Because the cache starts at -128, 130 is the index of the entry for 2. Autoboxing then takes care of the rest. When you declare Integer foo = 2 this gets autoboxed - i.e. converted to Integer.valueOf(2), which is now 3. When we do 2 + 2 the Integer object is unboxed to an int rather than the other way round, so foo + 2 becomes foo.intValue() + 2, which is 3 + 2. The rest of the code is just the neccessary hackery in order to beat the Java permissions system into submission. I didn't come up with this, but unfortunately I've lost the original article where I found this hack in. The above is my attempt at recreating it.

Snippets Manager replied on Mon, 2012/05/07 - 2:36pm

Nice one! Where does the number 130 come from? Please provide more information on the "internal".

Greg Miller replied on Mon, 2006/10/02 - 8:25pm

Yet another entry for the "How to write unmaintainable code" document.