Saturday, February 05, 2005

Reflection humor

Here is a funny bit of Java code:

private static class Root {
    protected Root(final String intFieldName) {
        try {
            final Field i = getClass().getDeclaredField(intFieldName);
            i.setAccessible(true);
            i.set(this, 4);

        } catch (final NoSuchFieldException e) {
            throw new IllegalArgumentException(intFieldName);

        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(intFieldName);
        }
    }
}

private static class Branch extends Root {
    private int i = 3;

    public Branch() {
        super("i");

        System.out.println("i = " + i);
    }
}

What does new Branch() print? A better question, why?

UPDATE: A great answer to my question.

Post a Comment