平常開發中常常須要將一個對象的屬性,賦值到另外一個對象中。java
常見的工具備不少,但都多少不夠簡潔,要麼不夠強大。git
咱們常常使用的 Spring BeanUtils 性能較好,可是特性不足。github
Bean-Mapping 提供了不少豐富的特性,便於平常開發。spring
若是你追求更加極致的性能,能夠考慮使用 asm 實現的模塊,該實現性能優於 spring BeanUtils 35% 左右。數組
支持對象屬性的淺拷貝 app
支持不一樣名稱字段的指定賦值框架
支持自定義字段屬性賦值的條件,好比目標字段不爲 null 才進行賦值maven
支持自定義字段值轉換,能夠轉換爲其餘類型,或者相同類型ide
支持屬性字段爲【對象】【集合】【數組】的賦值,對象賦值更加方便。工具
JDK1.7 及其以上版本
Maven 3.X 及其以上版本
<dependency> <groupId>com.github.houbb</groupId> <artifactId>bean-mapping-core</artifactId> <version>0.2.5</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; }
有時候咱們對於性能要求較高,而對便利性要求沒有這麼高。
本框架也提供了基於 asm 的複製方式,性能比 spring 好 35% 左右。
見文末的 benchmark。
<dependency> <groupId>com.github.houbb</groupId> <artifactId>bean-mapping-asm</artifactId> <version>0.2.5</version> </dependency>
和 BeanUtil#copyProperties(Object, Object)
使用相似,可是暫時不支持註解等更加豐富的功能。
BaseSource baseSource = buildBaseSource(); BaseTarget baseTarget = new BaseTarget(); AsmBeanUtil.copyProperties(baseSource, baseTarget);
實際工做中,咱們遇到的狀況會比這個複雜一些。
好比兩個字段名稱不一樣,咱們也想進行賦值,值得處理轉換等等。
Bean-Mapping 相關文檔:
07-BeanUtil#copyProperties(Object, Class) 方法
可見框架默認 bean-mapping 實現性能通常,涉及到了太多的特性,致使複製性能略低於 spring。
基於 reflectasm 實現的 asm-bean-mapping 的性能高於 spring。
代碼示例參見 BeanUtilBeanchmarkTest.java
相對 BeanCopier 這種實現方式,咱們的實現方式性能仍是有很大提高空間。
後期能夠考慮實現相似 BeanCopier 的方式。
這個框架的源代碼所有開源,也便於咱們學習。