有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java包的最终变量可以通过反射进行更改吗?

包最终变量可以通过反射进行更改吗

假设我有这个:

public class Widget {
  final int val = 23;
}

如果可以访问,可以通过反射更改val吗

如果是这样,是否有任何方法可以防止在不使用安全管理器的情况下发生这种情况


共 (3) 个答案

  1. # 1 楼答案

    试试这个

     Widget() {
         checkPerMission();
      }
         private void checkPerMission() {
             Class self = sun.reflect.Reflection.getCallerClass(1);
              Class caller = sun.reflect.Reflection.getCallerClass(3);
             if (self != caller) {
                 throw new java.lang.IllegalAccessError();
             }
    
     }
    
  2. # 2 楼答案

    事实证明,更改最终成员会导致反射获得的值与常规代码返回的值不同!这很可怕

    import java.lang.reflect.Field;
    
    public class Test {
    
        private static final class Widget {
            private final int val = 23;
    
            public int getVal() {
                return val;
            }
        }
    
        public static void main(String[] args) throws Exception {
            Widget w = new Widget ();
    
            Field m = Widget.class.getDeclaredField("val");
    
            m.setAccessible(true);
    
            m.set(w, 233);
    
            Field m1 = Widget.class.getDeclaredField("val");
            m1.setAccessible(true);
    
    
            System.out.println(m.get(w)); /// PRINT 233
            System.out.println(w.getVal()); /// PRINT 23
            System.out.println(m1.get(w)); /// PRINT 233
    
        }
    }
    
  3. # 3 楼答案

    对。请尝试以下代码:

    public static void main(String[] args) throws Exception {
        Widget w = new Widget ();
    
        Field m = Widget.class.getDeclaredField("val");
    
        m.setAccessible(true);
    
        m.set(w, 233);
    
        System.out.println(m.get(w)); /// PRINT 233
    }