Reflection and String immutability
Published by Kaustubh Saha on December 26th, 2018
One very powerful but risky tool is Reflection. Using reflection, you can break almost everything - from encapsulation to immutability
Here is a piece of code which breaks immutability of String class
import java.lang.reflect.Field;
public class MutableString {
public static void main(String[] args) throws Exception {
String someString = "IMMUTABLE";
Field field = Class.forName("java.lang.String").getDeclaredField("value");
field.setAccessible(true);
char[] value = (char []) field.get(someString);
String anotherString = "NOTREALLY";
for (int i=0; i<value.length; i++){
char c = anotherString.toCharArray()[i];
value[i]=c;
}
System.out.println(someString); // prints NOTREALLY
System.out.println("IMMUTABLE"); // WTF !!! prints NOTREALLY
}
}
Output:
NOTREALLY
NOTREALLY