changing final variables through reflection, why difference between static and non-static final variable

后端 未结 3 1499
清歌不尽
清歌不尽 2020-12-31 17:54

Please refer to the below code. When I run the code, I am able to change the value of a final non-static variable. But if I try to change the value of a final static variab

3条回答
  •  不思量自难忘°
    2020-12-31 18:51

    The javadoc is clear:

    If the underlying field is final, the method throws an IllegalAccessException unless setAccessible(true) has succeeded for this Field object and the field is non-static.

    From a JLS perspective, the exact behaviour of how reflection should work is not specified, but in JLS 17.5.4:

    Normally, a field that is final and static may not be modified.

    One workaround is to remove the final modifier through reflection.

提交回复
热议问题