Can you explain to me what happens executing this code? I know that it prints out “G’Day Mate.”, but how the Reflection catch the System.out.println? What happens at the Stack/Heap level? Thank you so much.
public static void main(String... args) {
System.out.println("Hello World");
}
static {
try {
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
value.set("Hello World", value.get("G'Day Mate."));
} catch (Exception e) {
throw new AssertionError(e);
}
}
The reflection does not “catch” the System.out. Of course you have picked and the most hardest example – String and that is because java String class is a very “interesting” class where each String is not an object but spawned in a pool of Strings and is by itself immutable.
What your code does is that in the java String class it statically(which would mean before execution time) sets the value of the String “Hello World” to “G`Day Mate.”. This means that whenever you use the string “Hello World” it would be changed to “G`Day Mate.”. Example:
Hope the example helps a bit.
Interesting remark, the code:
Produces output:
Which means that in the mapping the white space makes some difference, but I do not know how that effects the String object and the function of the reflect.