变更日志
JDK1.8 及其以上版本
Maven 3.X 及其以上版本
<dependency>
<groupId>com.github.houbb</groupId>
<artifactId>bean-mapping-core</artifactId>
<version>0.0.1</version>
</dependency>
提供一个简单的静态方法 copyProperties。
/** * 复制属性 * 将 source 中的赋值给 target 中名称相同,且可以赋值的类型中去。类似于 spring 的 BeanUtils。 * @param source 原始对象 * @param target 目标对象 */ public static void copyProperties(final Object source, Object target)
详情参见 bean-mapping-test 模块下的测试代码。
其中 BaseSource 对象和 BaseTarget 对象的属性是相同的。
public class BaseSource {
/**
* 名称
*/
private String name;
/**
* 年龄
*/
private int age;
/**
* 生日
*/
private Date birthday;
/**
* 字符串列表
*/
private List<String> stringList;
//getter & setter
}
我们构建 BaseSource 的属性,然后调用
BeanUtil.copyProperties(baseSource, baseTarget);
类似于 spring BeanUtils 和 Apache BeanUtils,并验证结果符合我们的预期。
/**
* 基础测试
*/
@Test
public void baseTest() {
BaseSource baseSource = buildBaseSource();
BaseTarget baseTarget = new BaseTarget();
BeanUtil.copyProperties(baseSource, baseTarget);
// 断言赋值后的属性和原来相同
Assertions.assertEquals(baseSource.getAge(), baseTarget.getAge());
Assertions.assertEquals(baseSource.getName(), baseTarget.getName());
Assertions.assertEquals(baseSource.getBirthday(), baseTarget.getBirthday());
Assertions.assertEquals(baseSource.getStringList(), baseTarget.getStringList());
}
/**
* 构建用户信息
* @return 用户
*/
private BaseSource buildBaseSource() {
BaseSource baseSource = new BaseSource();
baseSource.setAge(10);
baseSource.setName("映射测试");
baseSource.setBirthday(new Date());
baseSource.setStringList(Arrays.asList("1", "2"));
return baseSource;
}