Can 1.Java String be changed?
It has been assumed that the value of string in Java cannot be modified, mainly because the string is final and there is no set method for setting the value. However, the value can be changed by reflection mechanism.
Example 1
public class Test {public static void Main (string[] args) throws Exception { String s= "0123456789"; System.out.println ("Before Change: s=" + s); Field f = S.getclass (). Getdeclaredfield ("value"); F.setaccessible (true); F.set (S, New char[]{' A ', ' B ', ' C '}); System.out.println ("After change: s=" + s);} }
Example 1 results:
Before change: s=0123456789 changed: S=ABC
Example 1 cause
There is a private final char value[] member variable in the String class, and the value of the string class is stored in the Value property. This value can be changed by reflection to achieve the purpose of changing the value of the string class. Similarly, in this way, we can change the private member variable of the custom object.
Does the Java string type value really have to be changed?