1

リフレクションを使ってフィールドの値を変える裏技があることを知り、やってstatic finalみようと思いましたLong

    Field field = Long.class.getField("MIN_VALUE");
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, 2);
    System.out.println(Long.MIN_VALUE);

ただし、上記のコードは例外をスローすることも、の値を変更することもありませんLong.MIN_VALUE。なぜそうなのですか?

4

1 に答える 1

2

定数プリミティブ値は、using コードに直接コンパイルされます。実行時には、フィールドはアクセスされなくなります。したがって、後で変更しても、使用しているコードには影響しません。

私が見つけた最良の参考文献は、JLS のセクション 13.4.9 の次の段落です。

If a field is a constant variable (§4.12.4), then deleting the keyword final or
changing its value will not break compatibility with pre-existing binaries by
causing them not to run, but they will not see any new value for the usage of
the field unless they are recompiled. This is true even if the usage itself is
not a compile-time constant expression (§15.28). 
于 2013-08-29T14:52:43.960 に答える