简体   繁体   English

推土机是否允许从Enum转换为Enum?

[英]Does Dozer allow converting from Enum to Enum?

2 Enums: 2个枚举:

enum Source {

    WINTER,
    SPRING,
    SUMMER,
    AUTUMN
}

and

enum Dest {

    WINTER,
    SPRING,
    SUMMER,
    AUTUMN
}

attempting to convert Source to Dest with Dozer : 尝试使用DozerSource转换为Dest

DozerBeanMapper mapper = new DozerBeanMapper();

mapper.map(Source.WINTER, Dest.class);

Exception in thread "main" org.dozer.MappingException: java.lang.NoSuchMethodException: Dest.< init >() 线程“main”中的异常org.dozer.MappingException:java.lang.NoSuchMethodException:Dest。<init>()

But when I tried converting complex objects that contained the enums mentioned above, Dozer successfully converted it. 但是当我尝试转换包含上述枚举的复杂对象时,Dozer成功转换了它。

So, why can't Dozer convert Enum to Enum when they are not properties of complex objects? 那么,为什么当Dozer不是复杂对象的属性时,Dozer不能将Enum转换为Enum?

Dozer cannot map enums because it relies on the existence of the default no-argument public constructor. Dozer无法映射枚举,因为它依赖于默认的无参数公共构造函数的存在。 They can only be mapped when they are part of a larger POJO. 它们只能在它们是较大POJO的一部分时进行映射。 For example: 例如:

enum Source {

    WINTER,
    SPRING,
    SUMMER,
    AUTUMN
}

public class SourceClass{

  private Source season;

  public Source getSeason() {
    return season;
  }

  public void setSeason(Source season) {
    this.season = season;
  }

}

and

enum Dest {

    WINTER,
    SPRING,
    SUMMER,
    AUTUMN
}

public class DestClass{

  private Dest season;

  public Dest getSeason() {
    return season;
  }

  public void setSeason(Dest season) {
    this.season = season;
  }

}

Now this will work: 现在这将工作:

SourceClass source = new SourceClass();
source.setSeason(Source.AUTUMN);

DestClass dest = mapper.map(source, DestClass.class);

As alternative, if your enums share the same naming you could just do: 作为替代方案,如果您的枚举共享相同的命名,您可以这样做:

Dest mapped = Dest.valueOf(Source.WINTER.toString);

Note however that you lose type safety and your compiler won't warn you if either of the enum entries are renamed. 但请注意,如果重命名了任一枚举条目,则会丢失类型安全性并且编译器不会发出警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM