Monday, March 24, 2008

Abuse of Booleans ;-)

Today next chapter of abusing Java internals with using of reflections ;-)
In previous chapters we discussed problems: How many is 1+1 in Java and The Secret Life of String.

Two of well known facts about Boolean in Java are:
Boolean.valueOf(true) value is true
Boolean.valueOf(false) value is false

But how we will shown, not always ;p
import java.lang.reflect.Field;
public class HackBool {
static void fixBooleans() throws Exception {
Class boolClass = Boolean.class;
Field field = boolClass.getDeclaredField("value");
field.setAccessible(true);
field.setBoolean(Boolean.TRUE, false);
field.setBoolean(Boolean.FALSE, true);
}

public static void main(String[] args) throws Exception {
System.out.println("Boolean.valueOf("+true+")="+Boolean.valueOf(true));
System.out.println("Boolean.valueOf("+false+")="+Boolean.valueOf(false));
fixBooleans();
System.out.println("Boolean.valueOf("+true+")="+Boolean.valueOf(true));
System.out.println("Boolean.valueOf("+false+")="+Boolean.valueOf(false));
}
}


When we will try to execute this code we will see:

Boolean.valueOf(true)=true
Boolean.valueOf(false)=false
Boolean.valueOf(true)=false
Boolean.valueOf(false)=true


Two first lines looks good, but what with two last? ;-)

And what we will see after change of this code to this version:
import java.lang.reflect.Field;
public class HackBool {
static void fixBooleans() throws Exception {
Class boolClass = Boolean.class;
Field field = boolClass.getDeclaredField("value");
field.setAccessible(true);
field.setBoolean(Boolean.TRUE, false);
field.setBoolean(Boolean.FALSE, true);
}

public static void main(String[] args) throws Exception {
fixBooleans();
Boolean b = true;
if (b) System.out.println("TRUE :-)");
else System.out.println("FALSE :-(");
}
}

Correct answer is:
FALSE :-(

Why? Answer is easy, Boolean have two fields TRUE and FALSE, in fixBooleans() we changed values stored in variable value, for now when JVM tries to obtain value of TRUE it gets our change value false. That's whole secret ;-)

I will try to write next time something more interesting.

Similar postsbeta
How many i 1+1 in Java? ;-)
The Secret Life of String ;-)
How to create valid file name?
Recursion is evil ;-)
How to get negative number from size() in LinkedList in Java? ;-)

No comments:

Post a Comment