This is my first ques开发者_如何转开发tion 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
Patient: Doctor, doctor, it hurts when I do this (bangs arm with hammer).
Doctor: Don't do that then.
You really shouldn't be trying to mess with the contents of a string. Strings are designed to be immutable. Now I dare say it's a JVM bug that it crashes so dramatically (it doesn't on my box, btw - it would be useful if you'd tell us which operating system and JVM version you're using) but the simple answer is not to try to go behind the system's back.
it looks like that array of chars for "1"
and a number of other interned Strings (like "true"
, "false"
, "root"
, "class"
, etc) cannot be changed in Windows JVM. I.e. you cannot assign new values to array elements. But you can assign new array for that String object. Example
精彩评论