How to Transform Any Type of Java Bean With BULL

在跨团队或者跨系统的开发调用时,经常遇到 两个系统Java 代码命名不一致的情况,简单直接的办法就是写一堆get set

如果能拿到对方的jar 或者源码 亦可以使用对方的命名:

例如

对店铺的定义

A系统

public class shop{private long id ;private String name;private String address;}

B系统

public class  store{private Long  storeId;private String name;private String location;}

BULL 的使用

一、maven 的引入

The project provides two different builds, one compatible with jdk 8 (or above) and one with jdk 11 or above.

BULL提供了两个版本的jar
一个基于JDK8

一个基于JDK11

<dependency><groupId>com.hotels.beans</groupId><artifactId>bull-bean-transformer</artifactId><version>1.7.1</version>
</dependency>

二、特性

The macro features explained in this article are:

JAVA 对象转换 Bean transformation
JAVA 对象验证 Bean validation

三、对象转换

3.1

例如 给出两个不同的bean

public class FromBean {                                     public class ToBean {                           private final String name;                                  public BigInteger id;                                  private final BigInteger id;                                private final String name;                             private final List<FromSubBean> subBeanList;                private final List<String> list;                       private List<String> list;                                  private final List<ImmutableToSubFoo> nestedObjectList;private final FromSubBean subObject;                        private ImmutableToSubFoo nestedObject;                // all args constructor                                     // constructors                                         // getters and setters...                                    // getters and setters
}                                                           }

The transformation can be obtained with the following line of code:

ToBean toBean = new BeanUtils().getTransformer().transform(fromBean, ToBean.class);

简单的不同名称,成员变量同名的对象转换,spring 框架也也提供了类似功能。

3.2 不同成员名称的对象转换

Different Field Names Copy

需要组装一个map ,定义好转换的对应关系。

public class FromBean {                                     public class ToBean {                           private final String name;                                  private final String differentName;                   private final int id;                                       private final int id;                      private final List<FromSubBean> subBeanList;                private final List<ToSubBean> subBeanList;                 private final List<String> list;                            private final List<String> list;                    private final FromSubBean subObject;                        private final ToSubBean subObject;                    // all constructors                                         // all args constructor// getters...                                               // getters...
}                                                            }

We need to define proper field mappings and pass it to theTransformer object:

// the first parameter is the field name in the source object
// the second one is the the field name in the destination one
FieldMapping fieldMapping = new FieldMapping("name", "differentName");
Tansformer transformer = new BeanUtils().getTransformer().withFieldMapping(fieldMapping);

Then, we can perform the transformation:

ToBean toBean = transformer.transform(fromBean, ToBean.class);

3.3 不同层级的数据转换

FromBean 有一个成员也是 Bean 对象

需要FromsubBean 成员 转换成ToBean 成员变量

public class FromSubBean {                         private String serialNumber;                 private Date creationDate;                    // getters and setters...
}

and our source class and destination class are described as follow:

public class FromBean {                                     public class ToBean {                           private final int id;                                       private final int id;                      private final String name;                                  private final String name;                   private final FromSubBean subObject;                        private final String serialNumber;                 private final Date creationDate;                    // all args constructor                                     // all args constructor// getters...                                               // getters...
}                                                           }

…and that the values for fields serialNumber and creationDate into the ToBean object need to be retrieved from subObject, this can be done defining the whole path to the property dot separated:

FieldMapping serialNumberMapping = new FieldMapping("subObject.serialNumber", "serialNumber");
FieldMapping creationDateMapping = new FieldMapping("subObject.creationDate", "creationDate");
ToBean toBean = new BeanUtils().getTransformer().withFieldMapping(serialNumberMapping, creationDateMapping).transform(fromBean, ToBean.class);

3.4 使用构造方法

Different Field Names Defining Constructor Args
The mapping between different fields can also be defined by adding @ConstructorArg annotation next to constructor arguments.

The @ConstructorArg takes as input the name of the correspondent field in the source object.

public class FromBean {                                     public class ToBean {                           private final String name;                                  private final String differentName;                   private final int id;                                       private final int id;                      private final List<FromSubBean> subBeanList;                private final List<ToSubBean> subBeanList;                 private final List<String> list;                            private final List<String> list;                    private final FromSubBean subObject;                        private final ToSubBean subObject;                    // all args constructor// getters...                                                                }}
subBeanList                                                       public ToBean(@ConstructorArg("name") final String differentName, @ConstructorArg("id") final int id,
@ConstructorArg("subBeanList") final List<ToSubBean> @ConstructorArg(fieldName ="list") final List<String> list,@ConstructorArg("subObject") final ToSubBean subObject) {this.differentName = differentName;
this.id = id;this.subBeanList = subBeanList;this.list = list;
this.subObject = subObject; }// getters...

3.5 使用lamda 表达式转换

Apply a Custom Transformation on a Specific Field Lambda Function

The destination object has a totally different structure than the source object
目标对象和来源对象有不同的结构
We need to perform some operation on a specific field value before copying it
复制操作前需要处理数据
The destination object’s fields have to be validated
目标对象成员变量有校验
The destination object has an additional field than the source object that needs to be filled with something coming from a different source
目标对象有附加的成员变量,来源对象需要做特殊处理

Given the following Source class:

public class FromFoo {private final String id;private final String val;private final List<FromSubFoo> nestedObjectList;// all args constructor   // getters
}

And the following Destination class:

public class MixedToFoo {public String id;@NotNullprivate final Double val;// constructors// getters and setters
}
FieldTransformer<String, Double> valTransformer =new FieldTransformer<>("val",n -> Double.valueOf(n) * Math.random());
MixedToFoo mixedToFoo = new BeanUtils().getTransformer().withFieldTransformer(valTransformer).transform(fromFoo, MixedToFoo.class);

3.6 在源对象中缺少字段的情况下应用转换函数

public class FromBean {                                     public class ToBean {                           private final String name;                                  @NotNull                   private final BigInteger id;                                public BigInteger id;                      private final String name;                 private String notExistingField; // this will have value: sampleVal// all args constructor                                     // constructors...// getters...                                               // getters and setters...
}                                                           }

What we need to do is to assign a FieldTransformer function to a specific field:

FieldTransformer<String, String> notExistingFieldTransformer =new FieldTransformer<>("notExistingField", () -> "sampleVal");

以上代码赋予一个固定值,我们可以使用方法
The above functions will assign a fixed value to the field notExistingField, but we can return whatever, for example, we can call an external method that returns a value obtained after a set of operation, something like:
例如:
定义一个calculatevalue()

FieldTransformer<String, String> notExistingFieldTransformer =new FieldTransformer<>("notExistingField", () -> calculateValue());

However, in the end, we just need to pass it to the Transformer.

ToBean toBean = new BeanUtils().getTransformer().withFieldTransformer(notExistingFieldTransformer).transform(fromBean, ToBean.class);

4 Bean Validation

对象验证

The class validation against a set of rules can be precious, especially when we need to be sure that the object data is compliant with our expectations.

The “field validation” aspect is one of the features offered by BULL and it’s totally automatic — you only need to annotate your field with one of the existing javax.validation.constraints (or defining a custom one) and then execute the validation on this.

Given the following bean:

public class SampleBean {                           @NotNull                   private BigInteger id;                      private String name;                 // constructor// getters and setters...
}

An instance of the above object:

SampleBean sampleBean = new SampleBean();

And one line of code, such as:

new BeanUtils().getValidator().validate(sampleBean);

This will throw an InvalidBeanException, as the field id isnull.

参考资料:https://dzone.com/articles/how-to-transform-any-type-of-java-bean-with-one-li

JAVA Bean 转换工具 BULL 使用简介相关推荐

  1. 方便高效的JAVA对象转换工具

    1. 简介 lamia 是一个高性能的Java 实体映射工具, 使用简单的注解就能帮助你在编译期生成对应的转换代码 项目地址: github gitee 1.1 优势 方便灵活的编译期快速生成转换代码 ...

  2. 自定义java对象转换工具类

    背景 项目中经常有VO.PO.DTO等之间转换,由于apache工具类中BeanUtils.copyProperties及Json序列化反序列化方式转换性能比较低(阿里巴巴规范检查有提示不建议采用). ...

  3. Java金额转换工具类

    package com.healthy.prms.common.util;import java.math.BigDecimal;/*** @ClassName: RMBUtils* @Descrip ...

  4. java url工具_UrlTool官方版|UrlTool (java Url转换工具)下载v1.1-乐游网软件下载

    <UrlTool>是一款jave URL地址转换工具,可以利用这款工具将URL的某个字符进行路径转换,如果要获得真实的URL地址,就需要UrlTool的协助了,操作非常方便,免安装,直接点 ...

  5. JAVA日期转换工具类

    java中经常会用到日期的转换,所有自己整理了一套日期转换的工具类,方便使用. 首先导入 <dependency><groupId>joda-time</groupId& ...

  6. 提高工作效率的万能Java行列转换工具类

    1.说明 有时候工作中需要动态生成列,也就是不确定的列,那么在数据库层就不是那么好操作了,可以使用java工具类来实现. 本工具类是对市面上的工具类进行加工改造,可以通用于各种情况,更加灵活,下面我来 ...

  7. java 对象 转换 工具类_Java中excel与对象的互相转换的通用工具类编写与使用(基于apache-poi-ooxml)...

    通用excel与对象相互转换的工具类 前言:最近开发需要一个Excel批量导入或者导出的功能,之前用过poi-ooxml开发过一个导入的工具类,正好蹭着这次机会,把工具类的功能进行完善. 使用说明: ...

  8. java中文转换工具类

    /*** 获取中文首字母工具类** @author jiangjunjie*/ public class ChineseCharToEnUtil {/*** 转换为有声调的拼音字符串** @param ...

  9. java 文件格式转换工具

    有时候一个文件格式正确在某些情况下不一定能够正确播放,下面可以借助于java的一个类帮助我们把文件格式转正确 File source = new File(filepath); int index=a ...

最新文章

  1. IT职场中外企面试最爱提的问题TOP10
  2. 用python的turtle画圆-Python turtle 绘图画圆
  3. div在最顶层显示----弹出框效果
  4. 业务安全通用解决方案——WAF数据风控
  5. ORACLE TEXT DATASTORE PREFERENCE(六)
  6. 探索Julia(part14)--学生得分描述性统计案例
  7. 如何向微软 Docs 和本地化社区提交翻译贡献
  8. 如何使用PyTorch torch.max()
  9. [C/C++][经典探讨]类继承中,通过基类指针delete释放,是否会造成内存泄漏
  10. 数据库系统概论第五版(第 4 章 数据库安全性)笔记
  11. java 知网 语义 相似度,基于知网的词汇语义相似度计算-hownet!.doc
  12. python处理考勤数据_python连接中控考勤机分析数据
  13. html怎么设置内存当缓存,前端浏览器缓存怎么使用
  14. 葫芦娃游戏维护服务器怎么办,葫芦娃一直进不去 无法进入游戏解决方法
  15. Sixth season fourth episode,Joey lost his insurance!!!!!
  16. F5 GTM DNS 知识点和实验 3 -加速dns解析
  17. 单片机双机通信c语言,单片机双机通信(C51程序)
  18. 牛人的笔记本拆装-来自百度贴吧
  19. Mac os下时间戳转换
  20. 对象的创建、发布、逸出

热门文章

  1. 超详细讲解SpringMVC三层架构
  2. 【自然语言处理(NLP)】聊天机器人模块实现
  3. 音乐制作软件Ableton Live 10 Suite Mac激活教程
  4. HMS Core电商与游戏行业解决方案,全流程赋能开发者创新
  5. matlab mobile安装及使用
  6. 微信小程序 页面传参(url)参数过长报错解决办法
  7. CentOS7安装Docker和配置Docker Compose
  8. 报错:工作中心缺少公式CK430-PS
  9. 菜鸟站长的坎坷建站经历
  10. EOS创始人BM:会发行新币来作为火星和地球之间的通用货币!