Change private static final field using Java reflection

前端 未结 12 2616
天涯浪人
天涯浪人 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:09

    In case of presence of a Security Manager, one can make use of AccessController.doPrivileged

    Taking the same example from accepted answer above:

    import java.lang.reflect.*;
    
    public class EverythingIsTrue {
        static void setFinalStatic(Field field, Object newValue) throws Exception {
            field.setAccessible(true);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
    
            // wrapping setAccessible 
            AccessController.doPrivileged(new PrivilegedAction() {
                @Override
                public Object run() {
                    modifiersField.setAccessible(true);
                    return null;
                }
            });
    
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
            field.set(null, newValue);
        }
    
        public static void main(String args[]) throws Exception {      
          setFinalStatic(Boolean.class.getField("FALSE"), true);
          System.out.format("Everything is %s", false); // "Everything is true"
        }
    }
    

    In lambda expression, AccessController.doPrivileged, can be simplified to:

    AccessController.doPrivileged((PrivilegedAction) () -> {
        modifiersField.setAccessible(true);
        return null;
    });
    

提交回复
热议问题