您不能直接从枚举转换为对象。
您需要创建一个TypeMapper
和一个实现来处理转换。
类型转换
public class TypeConversion {
public static void main(String[] args) {
TypeDto t1 = TypeMapper.INSTANCE.typeToTypeDto(Type.T1);
TypeDto t2 = TypeMapper.INSTANCE.typeToTypeDto(Type.T2);
System.out.println(t1);
System.out.println(t2);
}
}
类型
public enum Type {
T1("T-One"),
T2("T-Two");
private final String description;
private Type(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
}
类型Dto
public class TypeDto {
private String description;
public TypeDto() {
this("");
}
public TypeDto(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return String.format("TypeDto { \"description\": \"%s\" }", description);
}
}
类型映射器
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper
public interface TypeMapper {
TypeMapper INSTANCE = Mappers.getMapper(TypeMapper.class);
@Mapping(source = "description", target = "description")
TypeDto typeToTypeDto(Type type);
}
TypeMapperImpl
public class TypeMapperImpl implements TypeMapper {
@Override
public TypeDto typeToTypeDto(Type type) {
if (type == null) {
return null;
}
return new TypeDto(type.getDescription());
}
}
您可以通过创建通用映射器使此映射器可重用。
枚举映射器
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@Mapper
public interface EnumMapper<T, U extends Enum<?>> {
@Mapping(target = "description")
T enumToObject(U type);
}
EnumMapperImpl
public abstract class EnumMapperImpl<T, U extends Enum<?>> implements EnumMapper<T, U> {
@Override
public T enumToObject(U type) {
if (type == null) {
return null;
}
return convert(type);
}
protected abstract T convert(U type);
}
然后你可以在你的 TypeMapper 中使用它。
类型映射器
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface TypeMapper extends EnumMapper<TypeDto, Type> {
TypeMapper INSTANCE = Mappers.getMapper(TypeMapper.class);
}
TypeMapperImpl
public class TypeMapperImpl extends EnumMapperImpl<TypeDto, Type> implements TypeMapper {
@Override
protected TypeDto convert(Type type) {
return new TypeDto(type.getDescription());
}
}