在开发过程中经常会有一个需求,就是类型转换 (把一个类转成另一个类)modelmapper就是一个提高生产力的工具
<!-- 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()); }
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()); }
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) { }
image.png
//属性赋值 private <S, D> void setDestinationValue(MappingContextImpl<S, D> context, MappingContextImpl<Object, Object> propertyContext, MappingImpl mapping) {}
image.png
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句