I know String is meant to be final, immutable and whats not.
However, I wondered for quite a while why it's so, and more importantly, how this is achieved.
Turns out, it is not achieved at all, it's merely a made up artificial restriction, at least so it seems.
Here' we have a "cat" string, and will fill it with "NYAN NYAN" content:
package hackstring;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args)
{
String str = "cat";
System.out.println(str);
modifyString(str, "NYAN NYAN");
System.out.println(str);
}
private static void modifyString(String modified, String newContent) {
try {
Field val = modified.getClass().getDeclaredField("value");
val.setAccessible(true);
Field count = modified.getClass().getDeclaredField("count");
count.setAccessible(true);
char[] injected = newContent.toCharArray();
count.set(modified, injected.length);
val.set(modified, injected);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Clearly, this is not meant to be done, but - it ACTUALLY WORKS!
cat
NYAN NYAN
So, if String is mutable, why are they feeding us this nonsense about it's immutability?
Like, if they wanted it to be truly immutable, why not make it a primitive type? This is just making fools of us, nothing else.
(This may not be strictly a question. Just something to think about..)