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

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 begin
score
class com.demo.zhengweiTest.Student end
class com.demo.zhengweiTest.People begin
name
class com.demo.zhengweiTest.People end
class com.demo.zhengweiTest.Animal begin
type
class com.demo.zhengweiTest.Animal end
type:人类 name:xiao li score:88

Process finished with exit code 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值