Bean-Mapping 用于 java 对象属性赋值。java
项目中常常须要将一个对象的属性,赋值到另外一个对象中。git
常见的工具备不少,但都多少不够简洁,要么不够强大。github
变动日志spring
JDK1.8 及其以上版本app
Maven 3.X 及其以上版本maven
<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 对象的属性是相同的。ui
public class BaseSource {
/** * 名称 */
private String name;
/** * 年龄 */
private int age;
/** * 生日 */
private Date birthday;
/** * 字符串列表 */
private List<String> stringList;
//getter & setter
}
复制代码
咱们构建 BaseSource 的属性,而后调用spa
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;
}
复制代码