本帖最后由 vmvm555 于 2013-1-23 19:10 编辑
众所周知,用private修饰的成员变量无法直接访问,但可以通过反射强制突破,拿到成员变量甚至修改它,但是如果该成员变量用final修饰符修饰,反射应该无法修改它吧,我的问题在下面一段代码- import java.lang.reflect.Field;
- public class TestArrayReflect {
- public static void main(String[] args) throws Exception {
- final Dog dog1 = new Dog(5, "red");
- Field field = dog1.getClass().getDeclaredField("age");
- field.setAccessible(true);
- System.out.println(field.get(dog1));
- field.setInt(dog1, 7);
- System.out.println(field.get(dog1));
- Field field2 = dog1.getClass().getDeclaredField("WEIGHT");
- field2.setAccessible(true);
- System.out.println(field2.get(null));
- field2.setInt(null, 25);
- System.out.println(field2.get(null));
- }
- }
- class Dog {
- private static final int WEIGHT = 20;
- private final int age;
- private String color;
-
- public Dog(int age, String color) {
- super();
- this.age = age;
- this.color = color;
- }
- public int getAge() {
- return age;
- }
- /* public void setAge(int age) {
- this.age = age;
- }*/
- public String getColor() {
- return color;
- }
- public void setColor(String color) {
- this.color = color;
- }
-
- }
复制代码 为什么用final修饰的成员变量能够更改它的值(final不代表该变量无法更改吗),就算能更改,为什么用 static final修饰的常量又不允许修改抛出了- Exception in thread "main" java.lang.IllegalAccessException: Can not set static final int field Dog.WEIGHT to (int)25
- at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:55)
- at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:79)
- at sun.reflect.UnsafeQualifiedStaticIntegerFieldAccessorImpl.setInt(UnsafeQualifiedStaticIntegerFieldAccessorImpl.java:111)
- at java.lang.reflect.Field.setInt(Field.java:802)
- at TestArrayReflect.main(TestArrayReflect.java:16)
复制代码 那位大侠来解释一下啊,谢谢
|