Changing private final fields via reflection

前端 未结 4 1034
鱼传尺愫
鱼传尺愫 2020-11-28 07:20
class WithPrivateFinalField {
    private final String s = \"I’m totally safe\";
    public String toString() {
        return \"s = \" + s;
    }
}
WithPrivateFinal         


        
4条回答
  •  伪装坚强ぢ
    2020-11-28 07:52

    This

    class WithPrivateFinalField {
        private final String s = "I’m totally safe";
        public String toString() {
            return "s = " + s;
        }  
    } 
    

    actually compiles like this:

    class WithPrivateFinalField {
        private final String s = "I’m totally safe";
        public String toString() {
            return "s = I’m totally safe";
        }  
    }
    

    That is, compile-time constants get inlined. See this question. The easiest way to avoid inlining is to declare the String like this:

    private final String s = "I’m totally safe".intern();
    

    For other types, a trivial method call does the trick:

    private final int integerConstant = identity(42);
    private static int identity(int number) {
        return number;
    }
    

提交回复
热议问题