Modifying final fields in Java

前端 未结 5 2011
故里飘歌
故里飘歌 2020-12-13 00:07

Let\'s start with a simple test case:

import java.lang.reflect.Field;

public class Test {
  private final int primitiveInt = 42;
  private final Integer wra         


        
5条回答
  •  情歌与酒
    2020-12-13 00:35

    There is a work around for this. if you set the value of the private static final filed in the static {} block it will work because it will not inline the fileld:

    private static final String MY_FIELD;
    
    static {
        MY_FIELD = "SomeText"
    }
    
    ...
    
    Field field = VisitorId.class.getDeclaredField("MY_FIELD");
    
    field.setAccessible(true);
    field.set(field, "fakeText");
    

提交回复
热议问题