This is my first question I hopefully don't make any terrible mistake. Assuming no SecurityManager is preventing me from doing this :
public static void main(String[] args) {
String str = "1";
System.out.println("str value before invoke fillStringValueWithX method: " + str);
fillStringValueWithX(str);
System.out.println("str value before invoke fillStringValueWithX method: " + str);
}
private static void fillStringValueWithX(String str) {
if (str != null) {
try {
Field fieldValue = String.class.getDeclaredField("value");
fieldValue.setAccessible(true);
char[] charValue = (char[]) fieldValue.get(str);
Arrays.fill(charValue, 'x');
fieldValue.setAccessible(false);
} catch (Exception e) {}
}
}
If the size of the string is 1 (the example above) the JVM crash (the crash dump shows an EXCEPTION_ACCESS_VIOLATION error) however if the size of the string is greater than 1 this code snippet works for me.
Note: I assume that the appropiate use for setting a field's value via reflection is using valueField.set(obj, value)
Field method but I want to know why the JVM crash...
Thanks