怎样用java反射机制,在知道属性名字的情况下,获得父类private 属性的值。

解决方案 »

  1.   

    public class Test{
    private String str="csdn";
    public void print(){
    System.out.println(str);
    }
    }
    //------------------------------------
    import java.lang.reflect.Field;public class ReflectionTest{public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException{
    Test t=new Test();
    t.print();
    Field[] f=t.getClass().getDeclaredFields(); for(int i=0;i<f.length;i++)
    {
    f[i].setAccessible(true);
    //System.out.println(f[i].getType());
    f[i].set(t, "japan");
    }
    t.print();
    }
    }
      

  2.   

    楼上正解.
    public void setAccessible(boolean flag)
                       throws SecurityException
    Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks. 
      

  3.   

    取能取到,用的话就要setAccessible了
      

  4.   

    setAccessible不要随便用,是有安全性限制的,可以通过配置关掉这个权限.正确的方法应该是在父类里面加上public的get ,set方法.然后通过反射去调