解决方案 »

  1.   

    刚刚又看到一个方法,getFields,本以为能把集成的变量都找出来,结果不好使
      

  2.   

    Person person = new Person(10, "LL");
            try {
                Field field = person.getClass().getDeclaredField("name");
                field.setAccessible(true);            field.set(person, "ERWA");
                
                System.out.println(person.getName());
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }要什么就反射取吧
      

  3.   


    我的意思是SuperMan的实例,想通过反射得到SuperMan父类Person的变量
      

  4.   

    getdeclaredfields应该是不行的, 它好像只能得到当前类所有属性
    getfields按理应该可以获取到当前类极其父类的所有属性, 当然前提是属性得是public的
      

  5.   

    SuperMan superMan = new SuperMan(10, "LL");
            try {
                //Field field = person.getClass().getDeclaredField("name");
                Field field =  superMan.getClass().getSuperclass().getDeclaredField("name");
                field.setAccessible(true);
                field.set(superMan, "ERWA");
                System.out.println(superMan.getName());
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }可以取到自己,再取个父类不就 OK?
      

  6.   

    public static void main(String[] args) throws Exception {
    Class<?> clazz = null;
    clazz = Class.forName("bianchengzhimei.SuperMan");
    Object p1 = clazz.newInstance();
    Field personNameField = null;
        for(;clazz != Object.class;clazz= clazz.getSuperclass()){
         try {
    personNameField = clazz.getDeclaredField("name");
    } catch (Exception e) {}
        }
        personNameField.setAccessible(true);
    personNameField.set(p1, "darlingFish"); System.out.println(personNameField.get(p1));
    }
      

  7.   

    7楼的方法基本上可以用了。另外推荐一种更规范的写法:Class<?> clazz = null;
        clazz = Class.forName("bianchengzhimei.SuperMan");
    //使用符合JavaBean规范的属性访问器
        PropertyDescriptor pd = new PropertyDescriptor("name", clazz);
    //调用setter
    Method writeMethod = pd.getWriteMethod(); //setName()
    writeMethod.invoke(obj, "test");
    //调用getter
    Method readMethod = pd.getReadMethod(); //getName()
    readMethod.invoke(obj);
      

  8.   

    private是私有变量,如果想给子类用,你就应该定义成protected啊。
    否则要这么多访问限定关键字干什么