vendredi 20 août 2021

Why I change the string s1 constant by reflection in java, the other s2, s3 also changed?

environment messages:

(env) λ java -version
openjdk version "1.8.0_242"
OpenJDK Runtime Environment (build 1.8.0_242-xxxxxx_JDK_xxxxx)
OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)

/*
 * Copyright (c) Google Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

package corejava.v1ch05.practice;

import java.lang.reflect.Field;
import java.util.Random;

public class ChangeString {

    private static void change(String message) throws NoSuchFieldException, IllegalAccessException {
        System.out.println(System.identityHashCode(message));

        Field f = message.getClass().getDeclaredField("value");
        System.out.print("Accessible: " + f.isAccessible());
        f.setAccessible(true);
        char[] v = (char[])f.get(message);
        Random random = new Random();
        char randomizedCharacter = (char) (random.nextInt(26) + 'a');
        v[0] = randomizedCharacter;

        System.out.println();
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        String s1 = " abcd";
        System.out.println("s1: " + System.identityHashCode(s1));

        String s2 = new String(" abcd");
        String s3 = " abcd";
        System.out.println("s2: " + System.identityHashCode(s2));
        System.out.println("s3: " + System.identityHashCode(s3));



        change(s1);
        // change(s2);
        System.out.print(s1 + " " + s2 + " " + s3);
    }
}


The results are as follows:

s1: 685325104
s2: 460141958
s3: 685325104
685325104
Accessible: false
tabcd tabcd tabcd

As I know, the string constant is stored in the string constant pool. store location(maybe it's wrong!): jdk1.6 Method Area jdk1.7 heap memory jdk1.8 local memory

I changed the s1, the s2, s3 reference also changed. It really mixed me up!





Aucun commentaire:

Enregistrer un commentaire