如何解决ModelMapper:将规则应用于所有类型的字段
我有一个包含很多字符串字段的 DTO(有些是其他类型的)。
将对象映射到另一个类似类的对象时,我需要对所有 String 类型的字段应用转换,在本例中为 trim()
。
所以,我有:
class MyDTO {
String name;
String type;
String company;
String status;
String whatever;
... (there are about 80 String fields)
int someNumber;
double otherNumber;
}
class DestinationDTO { // has just some fields of MyDTO
String name;
String type;
String company;
String whatever;
int somenumber;
}
我尝试过的:
Converter<String,String> myConverter = c -> c.getSource().trim();
ModelMapper mm = new ModelMapper();
...
mm.typeMap(MyDTO.class,DestinationDTO.class)
.addMappings(c -> c
.using(myConverter)
.map(MyDTO::getName,DestinationDTO::getName)
) // this applies to just one field,I need all String fields
有没有办法一次性指定一个类的所有 String 字段,而不必列出它们?
尝试搜索 modelmapper.org 文档,但我看到的只是一一配置字段。
有什么想法吗?
解决方法
您可以使用 converters 指定从一种类型到另一种类型的转换。源和目标类型可以相同。使用 addConverter<S,D>()
方法将通用转换器添加到 ModelMapper 本身(而不是单独添加到特定字段)。你可以这样使用它:
ModelMapper mm = new ModelMapper();
Converter<String,String> myConverter = new AbstractConverter<String,String>() {
protected String convert(String source) {
return source == null ? null : source.trim();
}
};
mm.addConverter(myConverter);
mm.getConfiguration().setFieldMatchingEnabled(true);
MyDTO source = new MyDTO();
source.name = " abc \t";
source.company = "\nd e f \n";
DestinationDTO target = mm.map(source,DestinationDTO.class);
System.out.printf("Target.name: '%s'%n",target.name);
System.out.printf("Target.company: '%s'%n",target.company);
输出将如预期:
Target.name: 'abc'
Target.company: 'd e f'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。