使用反射获取父类的属性并设值,适用于类中没有提供setter方法

来源:互联网 发布:ipad淘宝hd旧版本下载 编辑:程序博客网 时间:2024/05/08 02:29
package com.demo.zhengweiTest;/** * Created by zhengwei.wzw on 2015/7/22. */public class Animal {    protected String type;}package com.demo.zhengweiTest;/** * Created by zhengwei.wzw on 2015/7/22. */public class People extends Animal{    protected String name;}package com.demo.zhengweiTest;/** * Created by zhengwei.wzw on 2015/7/22. */public class Student extends People {    protected int score;    public String toString(){        String toString="type:"+type+" name:"+name+" score:"+score;        System.out.println(toString);        return toString;    }}package com.demo.zhengweiTest;import java.lang.reflect.Field;/** * Created by zhengwei.wzw on 2015/7/22. */public class Test {    public static void main(String args[])throws Exception{        Class clazz=Class.forName("com.demo.zhengweiTest.Student");        Student stu=(Student)clazz.newInstance();        Field typeField=null,nameField=null,scoreField=null;        for(;clazz != Object.class;clazz= clazz.getSuperclass()){            System.out.println(clazz+" begin");            try{                typeField = clazz.getDeclaredField("type");                if(typeField!=null)                    System.out.println(typeField.getName());            }catch(Exception e){}            try {                nameField = clazz.getDeclaredField("name");                if(nameField!=null)                    System.out.println(nameField.getName());            } catch (Exception e) {}            try {                scoreField = clazz.getDeclaredField("score");                if(scoreField!=null)                    System.out.println(scoreField.getName());            } catch (Exception e) {}            System.out.println(clazz+" end");        }        if(typeField!=null){            typeField.setAccessible(true);            typeField.set(stu,"人类");        }        if(nameField!=null){            nameField.setAccessible(true);            nameField.set(stu,"xiao li");        }        if(scoreField!=null){            scoreField.setAccessible(true);            scoreField.setInt(stu, 88);        }        stu.toString();    }}输出:class com.demo.zhengweiTest.Student beginscoreclass com.demo.zhengweiTest.Student endclass com.demo.zhengweiTest.People beginnameclass com.demo.zhengweiTest.People endclass com.demo.zhengweiTest.Animal begintypeclass com.demo.zhengweiTest.Animal endtype:人类 name:xiao li score:88Process finished with exit code 0

0 0
原创粉丝点击