12

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);
        }
    }
0

5 Answers 5

8

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:

String h ="Hello World";
System.out.println(h);
>>>G`Day Mate.

Hope the example helps a bit. Interesting remark, the code:

public static void main(String[] args){
        String h = "Hello";
        System.out.println(h);
        System.out.println("Hello");
    }
     static {
            try {
               Field value = String.class.getDeclaredField("value");
               value.setAccessible(true);
               value.set("Hello", value.get("G'Day Mate."));
            } catch (Exception e) {
              throw new AssertionError(e);
            }
        }

Produces output:

>>>G`Day
>>>G`Day

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.

10
  • 5
    Correct, but not very accurate. Each string is definitely an Object. String literals are String instances stored in a pool. And the code changes the value of the internal char array backing the String literal "Hello World".
    – JB Nizet
    Jul 28, 2012 at 12:33
  • You are probably right, I'm not expert on the String class... The point I "tried" to make is that it would affect only the String "Hello World" where "Hello Worldxxx" would not be affected, but probably did not explained it properly, sorry.
    – Alex Botev
    Jul 28, 2012 at 12:44
  • Would you know how intern() or string pool works? How does literal 'Hello World' still goes back to same object in string pool while its basic value has changed?
    – sgp15
    Jul 28, 2012 at 12:46
  • So, please let me understand. All String objects in Java are stored in a pool and retrieved by this so called "literal" which is the original value of the internal char array, Am I wrong? :) Jul 28, 2012 at 12:53
  • 1
    Additional note: the white space has nothing to do with that. The String object contains an array, an offset (0 by default), and a length. Your example code changes the array, but not the offset and the length, so it displays the 5 first characters of the new array (since "Hello" contains 5 characters).
    – JB Nizet
    Jul 28, 2012 at 13:35
1

Excellent question... what I could understand was

value.set("Hello World", value.get("G'Day Mate."));

replaced the value in string memory pool and kept the reference same. Mean in this program Hello World mentioned at any place will print G'Day Mate..

It's similar to case where in C language you modify the content of a variable using a pointer.

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);
 }
}
public static void main(String[] args){
    System.out.println("Hello World");
    System.out.println("Hell World");
    System.out.println("Hello orld");
    System.out.println("Hello World");
    String s = "Hello World";
    System.out.println(s);
}

prints

G'Day Mate.
Hell World 
Hello orld
G'Day Mate.
G'Day Mate.

So in String Pool the String has been modified but key remains Hello World.

Interestingly if in the statement

value.set("Hello World", value.get("G'Day Mate."));

the later String's length is less... it will throw ArrayIndexOutOfBoundException whenever String Hello World is accessed.

Hope this helps!!!

0

javadoc for java.lang.reflect.Field.set(object, value)

Sets the field represented by this Field object on the specified object argument to the specified new value. The new value is automatically unwrapped if the underlying field has a primitive type.

The operation proceeds as follows:

If the underlying field is static, the obj argument is ignored; it may be null.

Otherwise the underlying field is an instance field. If the specified object argument is null, the method throws a NullPointerException. If the specified object argument is not an instance of the class or interface declaring the underlying field, the method throws an IllegalArgumentException.

If this Field object is enforcing Java language access control, and the underlying field is inaccessible, the method throws an IllegalAccessException.

If the underlying field is final, the method throws an IllegalAccessException unless setAccessible(true) has succeeded for this Field object and the field is non-static. Setting a final field in this way is meaningful only during deserialization or reconstruction of instances of classes with blank final fields, before they are made available for access by other parts of a program. Use in any other context may have unpredictable effects, including cases in which other parts of a program continue to use the original value of this field.

If the underlying field is of a primitive type, an unwrapping conversion is attempted to convert the new value to a value of a primitive type. If this attempt fails, the method throws an IllegalArgumentException.

If, after possible unwrapping, the new value cannot be converted to the type of the underlying field by an identity or widening conversion, the method throws an IllegalArgumentException.

If the underlying field is static, the class that declared the field is initialized if it has not already been initialized.

The field is set to the possibly unwrapped and widened new value.

If the field is hidden in the type of obj, the field's value is set according to the preceding rules. Parameters: obj - the object whose field should be modified value - the new value for the field of obj being modified

0

This source code opens up some interesting techniques of java. Let's examine one by one.

At first we need to understand the flow of the code. Which part of the code will execute first?

The Static Initialization Block. Why? Let's consult with Java Language Specification (12.4) :

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.

And when does it occur? Again from JLS (12.4.1):

T is a class and a static method declared by T is invoked.

So we can come to the conclusion that static initiazlier will execute first before the main method.

Now, these two lines are using reflection:

Field value = String.class.getDeclaredField("value");
value.setAccessible(true);

We can break the fist line into two lines for simplicity:

Class<String> c=String.class;
Field value=c.getDeclaredField("value");

The fist line is retrieving the Reflected Class Object and the second line is retrieving a Field which represents the value field of the String class.

value.setAccessible(true) indicates that the reflected class object should suppress Java language access checking when it is used.(Reference).

Nex line under question is

value.set("Hello World", value.get("G'Day Mate."));

If we dive into .set() documenation we can see that we are calling the set(Object aObject,Object value) version of set. value.get("G'Day Mate.") is returning "G'Day Mate."'s value field's value which is actually a char[]. And with the call of set it replaces the value of "Hello World" object's value field with "G'Day Mate." object's value field.

The static block's code is explained.

Lets dive into main funciton. It's pretty simple. It should output Hello, world. But it is outputting G'Day Mate. Why? Because the Hello, world String object we created in the static initializer is the same as Hello, world object we are using in main function. Consulting with JLS again will shed light on it

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

This answer can help you to understand the fact more concisely.

So it is showing different value as we have already changed Hello,world object's value to G'Day, Mate.

But if you use new String("Hello world") in main function it will directly create a fresh instance of String rather than checking into its pool. So Hello world of main function would be differnt than Hello world of static initializer of which we have changed the value.

-4

From the Oracle (Java) docs:

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

Here is the entire link

1
  • 4
    So how does that changes the System.out.println("Hello World"); output ?? Jul 28, 2012 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.