0

i found this thread How does this Java code snippet work? (String pool and reflection) talking about changing the value of a string using reflection.

i perfectly understand the trick but with minor changes it does no more work as expected.

could you please explain what's going on in this code?

import java.lang.reflect.Field;

public class Parent {

   static String hello = "Hello";
   static {
       try {
           Field value = hello.getClass().getDeclaredField("value");
           value.setAccessible(true);
           value.set(hello, "Bye bye".toCharArray());
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   public static boolean check(String s){
       System.out.println(s + " " + "Hello");
       return s.equals("Hello");
   }
}

.

public class Child extends Parent{

   public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
       System.out.println(check("Hello"));
   }
}

Above code prints:

Hello Bye bye
false

why does the string litteral "Hello" reffer to "Bye bye" in Parent class but refer to "Hello" in Child class?

deiz21
  • 19
  • 4
  • Note that String handling has changed a lot starting from Java 9 (internal encodings, String deduplication, etc.), so old "tricks" may not work anymore. – Kayaman Nov 15 '19 at 13:42

1 Answers1

0

String constants like literals ("Hello"), method names, imported constants (public static final String) and so on are stored in the current class's constant pool.

In the Child's main, the Parent class is loaded, the static fields initialized. Then the child loads its Hello from its constant pool and interns it otherwise, as the values differ. The String.intern uses String.equals and that checks String.value - as per javadoc.

You could try a GrandPa class for a messup across classes. Or see that the Parent's hello is identical to an interned "Bye Bye". Though it might be that the Parent's interned String is no longer findable, as the hashCode is wrong, out-dated. One could create a String with a same hash code.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138