Change private static final field using Java reflection

前端 未结 12 2359
天涯浪人
天涯浪人 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 06:14

    Just saw that question on one of the interview question, if possible to change final variable with reflection or in runtime. Got really interested, so that what I became with:

     /**
     * @author Dmitrijs Lobanovskis
     * @since 03/03/2016.
     */
    public class SomeClass {
    
        private final String str;
    
        SomeClass(){
            this.str = "This is the string that never changes!";
        }
    
        public String getStr() {
            return str;
        }
    
        @Override
        public String toString() {
            return "Class name: " + getClass() + " Value: " + getStr();
        }
    }
    

    Some simple class with final String variable. So in the main class import java.lang.reflect.Field;

    /**
     * @author Dmitrijs Lobanovskis
     * @since 03/03/2016.
     */
    public class Main {
    
    
        public static void main(String[] args) throws Exception{
    
            SomeClass someClass = new SomeClass();
            System.out.println(someClass);
    
            Field field = someClass.getClass().getDeclaredField("str");
            field.setAccessible(true);
    
            field.set(someClass, "There you are");
    
            System.out.println(someClass);
        }
    }
    

    The output will be as follows:

    Class name: class SomeClass Value: This is the string that never changes!
    Class name: class SomeClass Value: There you are
    
    Process finished with exit code 0
    

    According to documentation https://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html

提交回复
热议问题