将父类的属性赋值给子类(利用反射)

转自:https://blog.csdn.net/qq_36354669/article/details/79807994

public class A {
    private String a;
    private String b;

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }
}
public class B extends A {
    private String c;
    private String d;

    public String getC() {
        return c;
    }

    public void setC(String c) {
        this.c = c;
    }

    public String getD() {
        return d;
    }

    public void setD(String d) {
        this.d = d;
    }
}

假如有A类和B类两个实体类,B类是继承于A类的,现在想要将A类中的 a属性和 b属性赋值给B类中的a属和b属性.第一次我尝试的方法是 将A类转为B类.这是一个错误的想法,因为在继承中是不能向下转型的.就比如一个乐器中有萨克斯和小提琴,你可以说小提琴是乐器,但是不能说乐器就是小提琴.然后又查阅资料,了解到使用反射能够在运行时得到一个类的各种信息,所以想法是将想要转变的父类和子类传入方法中,然后运用反射将父类中的参数名以及值取出来(此时想要取值的话是通过调用get参数名这个方法来取得,例如,有一个 msg参数,实体类中有getMsg方法才行).取出来后即可将值赋值给传入的子类.

下面是源代码

/**
 * @program: demo
 * @description: 反射
 * @author: [email protected]
 * @create: 2018-03-29 16:02
 **/
public class Demo11 {
    public static void main(String[] args) throws Exception {
        A a=new A();
        B b=new B();
        a.setA("a");
        a.setB("b");
        fatherToChild(a,b);
        System.out.println(b.getA());
    }


    public static <T>void fatherToChild(T father,T child) throws Exception {
        if (child.getClass().getSuperclass()!=father.getClass()){
            throw new Exception("child 不是 father 的子类");
        }
        Class<?> fatherClass = father.getClass();
        Field[] declaredFields = fatherClass.getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field field=declaredFields[i];
            Method method=fatherClass.getDeclaredMethod("get"+upperHeadChar(field.getName()));
            Object obj = method.invoke(father);
            field.setAccessible(true);
            field.set(child,obj);
        }

    }

    /**
     * 首字母大写,in:deleteDate,out:DeleteDate
     */
    public static String upperHeadChar(String in) {
        String head = in.substring(0, 1);
        String out = head.toUpperCase() + in.substring(1, in.length());
        return out;
    }
}

--------------------- 本文来自 Mr墨斗 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/qq_36354669/article/details/79807994?utm_source=copy

猜你喜欢

转载自blog.csdn.net/blueangle17/article/details/82892492
今日推荐