vendredi 15 novembre 2019

why does a same interned String literal have multiple values in this java code snippet?

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?





Aucun commentaire:

Enregistrer un commentaire