3

I found the below code snippet :

import java.lang.reflect.Field;
public class Test {
    public static void main(String[] args) {
        System.out.println("Inside main");
    }
    static {
        try {
            Field value = String.class.getDeclaredField("value");
            value.setAccessible(true);
            value.set("Inside main", value.get("Inside static bolck"));
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}

As per my understanding the output should be Inside static bolck but the output comes as Inside stat, the same character length of Inside main.
*If i increase the length of Inside main the output length is also getting increased.
Can anybody please explain? I do not have much knowledge in Reflection.

Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82

4 Answers4

4

On my JDK, String also has a count member, which would need to be updated to reflect the new length.

There's also an offset field, which may or may not need updating (probably not in the case).

Finally, there a hash field, which will no longer be correct after you've changed value.

Since this code relies on the undocumented details of a particular implementation of String, it is very fragile and highly non-portable. For example (hat tip @assylias), Oracle have removed the count and offset fields in JDK 7u6. If you were to upgrade from 7u5 to 7u6, all of a sudden your code would behave differently.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

The code makes assumptions about the actual implementation of the String class, e.g. that the class has a field called "value".

Since the internal state of the String class is not part of the API or the language specification, the actual implementation will vary between VMs from different vendors or even between different VM versions from the same vendor.

jarnbjo
  • 33,923
  • 7
  • 70
  • 94
0

"Inside main" contains 11 characters in value[] (value[] is private field in String class)
String value[] was initialized in first place which you define String "Inside main". Now you are changing value[]'s value which is private instance variable in String by using reflection then it has to fit only 11 character from the string Inside static bolck

AmitG
  • 10,365
  • 5
  • 31
  • 52
0

When you will vary "Inside main" you are allowed to value.get() the string <= "Inside main".Change -"Inside main" to "Inside main (8 spaces) " and it prints

"Inside static bolck"
joey rohan
  • 3,505
  • 5
  • 33
  • 70