在开发过程中经常会有一个需求,就是类型转换 (把一个类转成另一个类)modelmapper就是一个提高生产力的工具
- 入门
- 内置匹配器
- 自定义匹配器
- 源码映射解析
入门
- 方式1 (默认配置)
- 导入maven依赖
<!-- http://modelmapper.org/getting-started/-->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.0</version>
</dependency>
- 新建三个实体
public class AppleVo {
private String name ;
private String id ;
}
public class Apple {
private String id ;
private String name ;
private String createAge ;
}
public class AppleDTO {
private String name ;
private String create_age ;
}
- 测试
public static Apple apple;
public static List<Apple> apples;
/**
* 模拟数据
*/
static {
apple = new Apple();
apple.setName("black");
apple.setCreateAge("22");
apple.setId("1");
apples = new ArrayList<>(16);
Apple apple1 = new Apple("1", "red", "21");
Apple apple2 = new Apple("2", "blue", "22");
Apple apple3 = new Apple("3", "yellow", "23");
apples.add(apple1);
apples.add(apple2);
apples.add(apple3);
}
/**
*
* 属性名保持一致,采用默认规则
*/
public void test1() {
ModelMapper modelMapper = new ModelMapper();
AppleDTO appleDto = modelMapper.map(apple, AppleDTO.class);
System.out.println(appleDto.toString());
}
-
使用内置匹配策略
官方提供了多种匹配策略,可以去官网详细了解
public void test2() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
/** LOOSE松散策略 */
.setMatchingStrategy(MatchingStrategies.LOOSE);
AppleDTO appleDto = modelMapper.map(apple, AppleDTO.class);
System.out.println(appleDto.toString());
}
- 自定义映射规则
private static PropertyMap customField(){
/**
* 自定义映射规则
*/
return new PropertyMap<Apple, AppleDTO>() {
@Override
protected void configure() {
/**使用自定义转换规则*/
map(source.getCreateAge(),destination.getCreate_age());
}
};
}
public void test4(){
ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(customField()) ;
List<AppleDTO> userDTOS = modelMapper.map(apples,new TypeToken<List<AppleDTO>>() {}.getType());
System.out.println(userDTOS);
}
- 源码映射解析
在mappermodel中,一般情况下保持属性名一致即可以不用任何配置就可直接转换,mappermodel的原理是基于反射原理进行赋值的,或是直接对成员变量赋值的,走一波debug,如图
//入口方法
public <S, D> D map(S source, Class<S> sourceType, D destination,
TypeToken<D> destinationTypeToken, String typeMapName) {}
//类型映射
<S, D> D typeMap(MappingContextImpl<S, D> context, TypeMap<S, D> typeMap) {
}
//属性赋值
private <S, D> void setDestinationValue(MappingContextImpl<S, D> context,
MappingContextImpl<Object, Object> propertyContext, MappingImpl mapping) {}