父类属性值的copy

最近开发中遇到这样一个问题将父类的属性值copy到子类中,从而对子类添加一些其他属性。

父类:

package com.jalja.org.jms.test01;

import java.util.Date;

public class User {
    private Integer id;
    private String name;
    private Date time;
    public User() {
        super();
    }
    public User(String name, Date time) {
        super();
        this.name = name;
        this.time = time;
    }
    public User(Integer id, String name, Date time) {
        super();
        this.id = id;
        this.name = name;
        this.time = time;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getTime() {
        return time;
    }
    public void setTime(Date time) {
        this.time = time;
    }
}

子类:

package com.jalja.org.jms.test01;

public class UserVO extends User{
    private int sex;
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
}
package com.jalja.org.jms.test01;

import java.lang.reflect.Field;
import java.util.Date;

public class CopyObj {
    /**
     * 我们的业务是需要在现有的类上扩展一些属性供视图层使用
     * 1、在原有类上扩展一些属性也可以实现,但这样需要在别人的代码中直接更改,个人认为不是很好。
     * 2、写一个扩展类 UserVO 继承原类  User 
     * @param args
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        User user=new User("2131",new Date());
        //将父类强转为子类出现异常Exception in thread "main" java.lang.ClassCastException:
        //UserVO vo1=(UserVO) user;
        //vo1.setSex(0);
        
        UserVO vo2=(UserVO) copyObj(user,new UserVO());
        vo2.setSex(0);
        System.out.println(vo2.getName());
        
    }
    /** 子对象copy父对象的属性值
     *  copyObj 继承 targetObj 
     * @param targetObj  被copy的目标对象
     * @param copyObj  copy后的对象
     * @throws IllegalAccessException 
     * @throws IllegalArgumentException 
     */
    public static <T> T copyObj(T targetObj,T copyObj ) throws IllegalArgumentException, IllegalAccessException{
        Field [] fields=targetObj.getClass().getDeclaredFields();
        Field [] fieldsvo=copyObj.getClass().getSuperclass().getDeclaredFields();
        for(Field f:fields){
            f.setAccessible(true);
            for(Field f2:fieldsvo){
                f2.setAccessible(true);
                if(f.get(targetObj)!=null&& f.getName().toString().equals(f2.getName().toString())){
                    f2.set(copyObj,f.get(targetObj)) ; 
                }
             }
        }
        return copyObj;
    }
}

 

posted @ 2017-05-08 09:01  小禾点点  阅读(564)  评论(0编辑  收藏  举报