在開發(fā)過程中經(jīng)常會有一個需求,就是類型轉(zhuǎn)換 (把一個類轉(zhuǎn)成另一個類)modelmapper就是一個提高生產(chǎn)力的工具
- 入門
- 內(nèi)置匹配器
- 自定義匹配器
- 源碼映射解析
入門
- 方式1 (默認(rèn)配置)
- 導(dǎo)入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;
/**
* 模擬數(shù)據(jù)
*/
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);
}
/**
*
* 屬性名保持一致,采用默認(rèn)規(guī)則
*/
public void test1() {
ModelMapper modelMapper = new ModelMapper();
AppleDTO appleDto = modelMapper.map(apple, AppleDTO.class);
System.out.println(appleDto.toString());
}
-
使用內(nèi)置匹配策略
官方提供了多種匹配策略,可以去官網(wǎng)詳細(xì)了解
image.png
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());
}
- 自定義映射規(guī)則
private static PropertyMap customField(){
/**
* 自定義映射規(guī)則
*/
return new PropertyMap<Apple, AppleDTO>() {
@Override
protected void configure() {
/**使用自定義轉(zhuǎn)換規(guī)則*/
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中,一般情況下保持屬性名一致即可以不用任何配置就可直接轉(zhuǎn)換,mappermodel的原理是基于反射原理進(jìn)行賦值的,或是直接對成員變量賦值的,走一波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) {
}

image.png
//屬性賦值
private <S, D> void setDestinationValue(MappingContextImpl<S, D> context,
MappingContextImpl<Object, Object> propertyContext, MappingImpl mapping) {}

image.png
