类属性复制实现

来源:互联网 发布:google浏览器 for mac 编辑:程序博客网 时间:2024/05/01 11:29
  • 实现功能
    a. 不同java 对象之间相同属性值的拷贝
  • 引用第三方jar再次外包装进行实现(commons-beanutils)
        <groupId>commons-beanutils</groupId>        <artifactId>commons-beanutils</artifactId>        <version>1.9.2</version>        </dependency>
  • 实现源代码
import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;import java.util.List;import java.util.Set;import org.apache.commons.beanutils.BeanUtils;public class BeanAdapter<T,E> {    private T destType;    public BeanAdapter(T destType){        if(destType == null){            throw new NullPointerException();        }        this.destType = destType;    }    public List<T> copyProperties2List(Collection<? extends E> origElements) throws Exception{        List<T> destList = new ArrayList<T>();        if(origElements == null || origElements.size() == 0){            return destList;        }        return (List<T>) copyProperties(destList,origElements);    }    public Set<T> copyProperties2Set(Collection<? extends E> origElements) throws Exception{        Set<T> destSet = new HashSet<T>();        if(origElements == null || origElements.size() == 0){            return destSet;        }        return (Set<T>) copyProperties(destSet,origElements);    }    private Collection<T> copyProperties(Collection<T> dest,Collection<? extends E> origElementList) throws Exception{        for (E element : origElementList) {            @SuppressWarnings("unchecked")            T destObject = (T) destType.getClass().newInstance();            BeanUtils.copyProperties(destObject, element);            dest.add(destObject);        }        return dest;    }}
  • 实现的反思

  1. T destType 定义是否是必须定义
T destObject = (T) destType.getClass().newInstance();

是为了创建具体的目的对象而用
2. 返回不同的Collection< T > 是否有必要在接口内部进行强制的定义,通过外部依赖的方式是不是更好

prublic Collection<T> copyProperties(Collection<T> dest,Collection<? extends E> origElementList)

0 0