Change private static final field using Java reflection

前端 未结 12 2636
天涯浪人
天涯浪人 2020-11-21 05:52

I have a class with a private static final field that, unfortunately, I need to change it at run-time.

Using reflection I get this error: java.lan

12条回答
  •  暖寄归人
    2020-11-21 06:10

    If your field is simply private you can do this:

    MyClass myClass= new MyClass();
    Field aField= myClass.getClass().getDeclaredField("someField");
    aField.setAccessible(true);
    aField.set(myClass, "newValueForAString");
    

    and throw/handle NoSuchFieldException

提交回复
热议问题