jar:commons-beanutils-1.9.3.jar、commons-lang-2.6.jar、dozer-5.3.2.jar、jcl-over-slf4j-1.7.25.jar、slf4j-api-1.7.25.jar
依赖:
<dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>5.4.0</version> </dependency>
工具类
package dozer; import java.util.ArrayList; import java.util.List; import org.dozer.DozerBeanMapper; import org.dozer.Mapper; /** * * @Title: DozerUtil.java * @Package * @Description: 将一个对象的属性复制到另一个对象或者list中 * @author licy * @date 2018年11月8日 * @version V1.0 */ public class DozerUtil { private static Mapper mapper = new DozerBeanMapper(); public static <T> List<T> transforList(List<?> sources, Class<T> clazz) { List<T> list = new ArrayList<>(); if (sources == null) { return list; } for (Object o : sources) { T t = transfor(o, clazz); list.add(t); } return list; } public static void transfor(Object source, Object target) { if (source == null || target == null) { return; } mapper.map(source, target); } public static <T> T transfor(Object source, Class<T> target) { if (source == null) { return null; } return mapper.map(source, target); } }
测试类
package dozer; /** * @Title: DozerBean.java * @Package dozer * @Description: TODO(用一句话描述该文件做什么) * @author licy * @date 2018年11月9日 * @version V1.0 */ public class DozerBean { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public DozerBean() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "DozerBean [id=" + id + ", name=" + name + ", age=" + age + "]"; } public DozerBean(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } }
测试执行类
package dozer; public class TestDozerUtil { public static void main(String[] args) { DozerBean dBean1 = new DozerBean(1,"a",1); DozerBean dBean2 = DozerUtil.transfor(dBean1, DozerBean.class); System.out.println(dBean2.toString()); } }