🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1. 两个字段数量不同的枚举类** ```java public enum Dog { XIAOHUANG, DAHUANG, DOG_1, DOG_2, DOG_3, } public enum DogDto { XIAOHUANG, DAHUANG, DOG_DTO, } ``` **2. 映射接口** ```java @Mapper public interface DogMapper { DogMapper INSTANCE = Mappers.getMapper(DogMapper.class); /** * 1)两个枚举类的属性名相同时会自动映射,不需要显示处理。 * 2)DOG_1、DOG_2、DOG_3都可以映射到DOG_DTO。 */ @ValueMapping(source = "DOG_1", target = "DOG_DTO") @ValueMapping(source = "DOG_2", target = "DOG_DTO") @ValueMapping(source = "DOG_3", target = "DOG_DTO") DogDto toDto(Dog source); /** * MappingConstants.ANY_REMAINING 可以让source剩余的未匹配的属性都可以映射到DOG_DTO */ @ValueMapping(source = MappingConstants.ANY_REMAINING, target = "DOG_DTO") DogDto toDto2(Dog source); /** * MappingConstants.ANY_UNMAPPED 可以让source未使用@ValueMapping(source="..",)明确指定的 * 属性都可以映射到DOG_DTO。 */ @ValueMapping(source = MappingConstants.ANY_UNMAPPED, target = "DOG_DTO") DogDto toDto3(Dog source); } ``` **3. 测试** ```java @Test public void testDogMapper() { DogDto dogDto = DogMapper.INSTANCE.toDto(Dog.XIAOHUANG); DogDto dogDto1 = DogMapper.INSTANCE.toDto(Dog.DOG_1); DogDto dogDto2 = DogMapper.INSTANCE.toDto2(Dog.DOG_1); DogDto dogDto3 = DogMapper.INSTANCE.toDto3(Dog.DAHUANG); System.out.println("dogDto:" + dogDto); //dogDto:XIAOHUANG System.out.println("dogDto1:" + dogDto1);//dogDto1:DOG_DTO System.out.println("dogDto2:" + dogDto2);//dogDto2:DOG_DTO System.out.println("dogDto3:" + dogDto3);//dogDto3:DOG_DTO } ``` **4. 查看映射接口被Mapstruct编译后的代码** ```java public class DogMapperImpl implements DogMapper { public DogMapperImpl() { } public DogDto toDto(Dog source) { if (source == null) { return null; } else { DogDto dogDto; switch(source) { case DOG_1: dogDto = DogDto.DOG_DTO; break; case DOG_2: dogDto = DogDto.DOG_DTO; break; case DOG_3: dogDto = DogDto.DOG_DTO; break; case XIAOHUANG: dogDto = DogDto.XIAOHUANG; break; case DAHUANG: dogDto = DogDto.DAHUANG; break; default: throw new IllegalArgumentException("Unexpected enum constant: " + source); } return dogDto; } } public DogDto toDto2(Dog source) { if (source == null) { return null; } else { DogDto dogDto; switch(source) { case XIAOHUANG: dogDto = DogDto.XIAOHUANG; break; case DAHUANG: dogDto = DogDto.DAHUANG; break; default: dogDto = DogDto.DOG_DTO; } return dogDto; } } public DogDto toDto3(Dog source) { if (source == null) { return null; } else { switch(source) { default: DogDto dogDto = DogDto.DOG_DTO; return dogDto; } } } } ```