Service层在做业务处理的时候,通常会把DAO层的domain类转化成DTO,并向上层提供服务。
对于类变化不大的情况,可以使用beanUtils做处理。
为了实现通用性,我封装了该类,代码如下:
import net.xuele.common.utils.format.JsonUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* 拷贝对象属性到新的类,使用了commons的BeanUtils
*
* @author wull
*/
public class CopyObjListUtil{
private static Logger logger = LoggerFactory.getLogger(CopyObjListUtil.class);
public static <T, S> List<T> convert(Collection<S> srcList, Class<T> targetClazz) {
if (CollectionUtils.isEmpty(srcList)) {
return Collections.emptyList();
}
T target = null;
try {
List<T> dist = new ArrayList<T>();
for (S src : srcList) {
//目标类注意必须实现空构造函数
target = targetClazz.newInstance();
BeanUtils.copyProperties(target, src);
dist.add(target);
}
return dist;
} catch (Exception e) {
logger.error("对象{}复制属性出错:{}", targetClazz.getSimpleName(), JsonUtils.toJson(srcList));
throw new IllegalArgumentException("对象" + targetClazz.getSimpleName() + "复制属性出错", e);
}
}
/**
*
* @param src
* @param targetClazz
* @return
*/
public static <T, S> T convert(S src, Class<T> targetClazz) {
if (src == null ) {
return null;
}
try {
//目标类注意必须实现空构造函数
T target = targetClazz.newInstance();
BeanUtils.copyProperties(target, src);
return target;
} catch (Exception e) {
logger.error("对象{}复制属性出错:{}", targetClazz.getSimpleName(), JsonUtils.toJson(src));
throw new IllegalArgumentException("对象" + targetClazz.getSimpleName() + "复制属性出错", e);
}
}
public static void main(String[] args) {
TestCls srcCls = new TestCls();
srcCls.setName("张三");
List<TestCls> srcList = new ArrayList<TestCls>();
srcList.add(srcCls);
List<TestDTO> targetList = CopyObjListUtil.convert(srcList, TestDTO.class);
System.out.println(JsonUtils.toJson(targetList));
}
public static class TestCls {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* 目标类必须有无参构造参数
*/
public static class TestDTO implements Serializable {
private static final long serialVersionUID = -1470656206298577026L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}