Java Reference
In-Depth Information
< Day Day Up >
Puzzle 80: Further Reflection
This program produces its output by printing an object that is created reflectively. What does the
program print?
public class Outer {
public static void main(String[] args) throws Exception {
new Outer().greetWorld();
}
private void greetWorld() throws Exception {
System.out.println(Inner.class.newInstance());
}
public class Inner {
public String toString() {
return "Hello world";
}
}
}
Solution 80: Further Reflection
This program looks like yet another unusual variant on the usual
Hello world
program. The
main
method in
Outer
creates an
Outer
instance and calls its
greetWorld
method, which prints the string
form of a new
Inner
instance that it creates reflectively. The
toString
method of
Inner
always
returns the standard greeting, so the output of the program should, as usual, be
Hello world
. If you
try running it, you'll find the actual output to be longer and more confusing:
Search WWH ::
Custom Search