脚本宝典收集整理的这篇文章主要介绍了java bean 对象属性复制框架BeanMapping-01-入门案例,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
项目简介
Bean-Mapping 用于 java 对象属性赋值。
项目中经常需要将一个对象的属性,赋值到另一个对象中。
常见的工具有很多,但都多少不够简洁,要么不够强大。
特性
- 支持对象属性的浅拷贝
变更日志
变更日志
快速开始
准备
JDK1.8 及其以上版本
Maven 3.x 及其以上版本
maven 项目依赖
<dependency> <groupId>com.github.houbb</groupId> <artifactId>bean-mapping-core</artifactId> <version>0.0.1</version> </dependency>
核心类说明
BeanUtil
/** * 复制属性 * 将 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; }
以上是脚本宝典为你收集整理的java bean 对象属性复制框架BeanMapping-01-入门案例全部内容,希望文章能够帮你解决java bean 对象属性复制框架BeanMapping-01-入门案例所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。