Search This Blog

Wednesday, 17 November 2010

No, I'm still not keeping these to myself ;-)

The usual drill here - what does it print and why?

...yes, it does compile :-)


import java.lang.reflect.Field;

public class Outer {

private class Inner {
private int field1 = 1;
private int field2 = 2;
private int field3 = 3;
private int field4 = 4;
}

public Outer() {
int count=0;
Inner inner = new Inner();
for(Field field : Inner.class.getDeclaredFields()) {
field.setAccessible(true);
try {
count += field.getInt(inner);
}
catch(IllegalAccessException ex) {}
}
System.out.print(count);
}

public static void main(String[] arguments) {
new Outer();
System.out.println(Inner.class.getDeclaredFields().length);
}
}

No comments:

Post a Comment