java 使用MapStructMap枚举字段

roqulrg3  于 2023-01-11  发布在  Java
关注(0)|答案(3)|浏览(235)

我想Map两个模型,其中每个模型都有几乎相同的枚举。
第一个模型具有枚举:

public enum EventSource {
  BETRADAR("SOURCE_BETRADAR"),
  BETGENIUS("SOURCE_BETGENIUS"),
  BETCONSTRUCT("SOURCE_BETCONSTRUCT"),
  MODEL("SOURCE_MODEL");

第二个模型具有枚举:

public enum SportEventSource implements ProtocolMessageEnum {
  SOURCE_UNKNOWN(0),
  SOURCE_BETRADAR(1),
  SOURCE_BETGENIUS(2),
  SOURCE_BETCONSTRUCT(3),
  UNRECOGNIZED(-1);

我有这样的自定义Map方法:

@Named("eventSourceConverter")   
default EventSource eventSourceConverter(SportEventSource source) {
        switch (source) {
          case SOURCE_MODEL:
            return EventSource.MODEL;
          case SOURCE_BETCONSTRUCT:
            return EventSource.BETCONSTRUCT;
          case SOURCE_BETGENIUS:
            return EventSource.BETGENIUS;
          case SOURCE_BETRADAR:
            return EventSource.BETRADAR;
          default:
            return EventSource.MODEL;
        }   
}

然后我使用:

@Mapping(target = "mainSource", source = "source", qualifiedByName = "eventSourceConverter")
  AdapterCompetitor protoToModel(Competitor proto);

但得到:

error: The following constants from the property "SportEventSource source" enum have no corresponding constant in the "*source*" enum and must be mapped via adding additional mappings: SOURCE_UNKNOWN, SOURCE_BETRADAR, SOURCE_BETGENIUS, SOURCE_BETCONSTRUCT, UNRECOGNIZED.
  AdapterCompetitor protoToModel(Competitor proto);

我还创建了如下枚举Map器:

@ValueMappings({
      @ValueMapping(source = "SOURCE_BETRADAR", target = "BETRADAR"),
      @ValueMapping(source = "SOURCE_BETGENIUS", target = "BETGENIUS"),
      @ValueMapping(source = "SOURCE_BETCONSTRUCT", target = "BETCONSTRUCT"),
      @ValueMapping(source = "SOURCE_MODEL", target = "MODEL"),
      @ValueMapping(source = "SOURCE_UNKNOWN", target = "MODEL"),
      @ValueMapping(source = "UNRECOGNIZED", target = "MODEL")
  })
  EventSource eventSourceToSportEventSource(SportEventSource source);

但是我不需要把它分开,只希望那个枚举域在内部Map中Map,简单地说-当我做AdapterCompetitor protoToModel(Competitor proto)枚举时,它也应该被Map。
谢谢!
对不起我的工程师,希望我的问题有意义:)

fwzugrvs

fwzugrvs1#

这可以使用@ValueMapping实现

xzlaal3s

xzlaal3s2#

我认为最方便的方法就是在Map器中设置一个默认方法

default ProblemStatus problemStatusFromString(String status) {
    return ProblemStatus.get(status);
}

default String problemStatusToString(ProblemStatus problemStatus) {
    return problemStatus.getValue();
}
ktecyv1j

ktecyv1j3#

我以前

@Mapper(componentModel = "spring")
public interface ConverterMapper {
  @Named("UnitValueConverter")
  default Long unitValueConverter(UInt64Value value) {
    return value.getValue();
  }

作为一个包含所有命名Map器的接口,就像上面那样,然后我

@Mapper(componentModel = "spring")
public interface EventMapper extends ConverterMapper

问题是我没有将@Mapper注解添加到ConverterMapper接口

相关问题