2

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

4

2 に答える 2

3

患者: ドクター、ドクター、これをすると痛いです (ハンマーで腕を叩く)。

医者: では、それをしないでください。

文字列の内容をいじろうとするべきではありません。文字列は不変になるように設計されています。今、私はそれが非常に劇的にクラッシュするのはJVMのバグだとあえて言います(ところで、私のボックスにはありません-使用しているオペレーティングシステムとJVMのバージョンを教えていただければ助かります)が、簡単な答えはシステムの後ろに行こうとしないでください。

于 2010-12-06T19:18:24.213 に答える
0

Windows JVMでは、その文字の配列と"1"他の多くのインターンされた文字列 ( "true"、、、、など) を変更できないようです。つまり、配列要素に新しい値を割り当てることはできません。ただし、その String オブジェクトに新しい配列を割り当てることができます。"false""root""class"

于 2012-01-04T16:07:15.470 に答える