samedi 2 avril 2016

String literals, interning and reflection

I'm trying to find a third solution to this question.

I can't understand why this doesn't print false.

public class MyClass {

    public MyClass() {
        try {
            Field f = String.class.getDeclaredField("value");
            f.setAccessible(true);
            f.set("true", f.get("false"));
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        MyClass m = new MyClass();
        System.out.println(m.equals(m));
    }
}

Surely, because of string interning, the "true" instance being modified is exactly the same one used in the print method of PrintStream?

public void print(boolean b) {
    write(b ? "true" : "false");
}

What am I missing?

Edit

An interesting point by @yshavit is that if you add the line

System.out.println(true);

before the try, the output is

true
false





Aucun commentaire:

Enregistrer un commentaire