Is a Java string really immutable? -
We all know that string
is irreversible in Java, but check the following code:
string s1 = "hello world"; String s2 = "hello world"; String s3 = s1.substring (6); Println (S1); // hello world system Out.printline (s2); // hello world system OutprintLine (S3); // World Field field = string.clash.getdcloidfield ("value"); Field.setAccessible (true); Four [] value = (four []) field.get (s1); Value [6] = 'J'; Value [7] = 'A'; Value [8] = 'V'; Value [9] = 'A'; Value [10] = '!'; Println (S1); // hello java! Println (s2); // hello java! Println (S3); // World
Why does this program work like this? Why the value of s1
and s2
have changed, but s3
not
string
is irreversible * But this only means that you can not change it using your public API.
What you are doing here is to stop the normal API using reflection. Similarly, you can change the value of anman, change the lookup table used in integer autoboxing etc.
Now, the reason s1
and s2
change value, is that they both refer to the same interned string. The compiler does this (as outlined by other answers).
The reason s3
does not actually be a little surprising to me, as I thought it was value
Array will share (before Java 7u6) However, given the source code of string
, we can see that the value
character array for a substring actually copies ( using Arrays.copyOfRange (..)
). This is why it becomes unchanged.
To do such things, you can install a SecurityManager
to avoid malicious code. But keep in mind that some libraries rely on using these type of reflection tricks (usually ORM equipment, AOP library etc.).
*) I initially wrote that string
s is not actually immutable, just "effective irreversible" it is misleading in the current implementation of the string
Where the value
array is actually marked personal finals
. It is still noticeable, however, there is no way to declare the array in an irreversible mode, so with the proper access modifier, it should not be exposed outside its orbit.
This topic is considered very popular, here are some suggestions: From Java Zone 2009, which covers many issues in OP, along with other reflections. Well ... Madness
This is why it is sometimes useful and why, most of the time, you should avoid it. : -)
Comments
Post a Comment