Change private static final field using Java reflection

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

    A little curiosity from the Java Language Specification, chapter 17, section 17.5.4 "Write-protected Fields":

    Normally, a field that is final and static may not be modified. However, System.in, System.out, and System.err are static final fields that, for legacy reasons, must be allowed to be changed by the methods System.setIn, System.setOut, and System.setErr. We refer to these fields as being write-protected to distinguish them from ordinary final fields.

    Source: http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.4

提交回复
热议问题