簡體   English   中英

使用反射更改Long.MIN_VALUE

[英]Changing Long.MIN_VALUE using reflection

我知道有一個技巧可以使用反射來更改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的值。 為什么會這樣呢?

常量基元值直接編譯為使用代碼。 在運行時,不再訪問該字段。 因此,事后更改對使用代碼沒有任何影響。

我發現的最佳參考是JLS13.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). 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM