簡體   English   中英

更改 java 中的 static 最終字段 12+

[英]Change static final field in java 12+

這個問題與Change private static final field using Java reflection密切相關。 在那里,有人詢問如何更改private static final變量。


但是,該問題的答案在 Java 12+ 中不起作用,因為您無法使用反射訪問java.lang.reflect.Field的私有變量。

盡管如此,當您嘗試這樣做時,您最終會得到如下堆棧跟蹤:

Exception java.lang.NoSuchFieldException: modifiers
      at Class.getDeclaredField (Class.java:2412)
      at <your call of Field.class.getDeclaredField("modifiers").setAccessible(true)>

有沒有辦法在這些版本中改變這樣的常數?

我可以想象使用 JNI/JNA 是可能的。

您可以使用Unsafe

public class Example
{
    // javac will inline static final Strings, so let's say it's Object
    private static final Object changeThis = "xxx";

    public static void main(String... args) throws Exception
    {
        final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        final Unsafe unsafe = (Unsafe) unsafeField.get(null);

        System.out.println("before = " + changeThis);

        final Field ourField = Example.class.getDeclaredField("changeThis");
        final Object staticFieldBase = unsafe.staticFieldBase(ourField);
        final long staticFieldOffset = unsafe.staticFieldOffset(ourField);
        unsafe.putObject(staticFieldBase, staticFieldOffset, "it works");

        System.out.println("after = " + changeThis);
    }
}

結果:

before = xxx
after = it works

暫無
暫無

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

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