简体   繁体   English

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

[英]Change static final field in java 12+

This question is strongly related to Change private static final field using Java reflection .这个问题与Change private static final field using Java reflection密切相关。 There, it was asked, how to change a private static final variable.在那里,有人询问如何更改private static final变量。


However, the answers on that question do not work in Java 12+ as you cannot access private variables of java.lang.reflect.Field using Reflection.但是,该问题的答案在 Java 12+ 中不起作用,因为您无法使用反射访问java.lang.reflect.Field的私有变量。

When you try to do it despite that, you will end up with a stack trace like:尽管如此,当您尝试这样做时,您最终会得到如下堆栈跟踪:

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

Is there any way to change such a constant in those versions?有没有办法在这些版本中改变这样的常数?

I could imagine being possible utilizing JNI/JNA.我可以想象使用 JNI/JNA 是可能的。

You can use Unsafe .您可以使用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);
    }
}

Result:结果:

before = xxx
after = it works

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM