简体   繁体   中英

Does Dozer allow converting from Enum to Enum?

2 Enums:

enum Source {

    WINTER,
    SPRING,
    SUMMER,
    AUTUMN
}

and

enum Dest {

    WINTER,
    SPRING,
    SUMMER,
    AUTUMN
}

attempting to convert Source to Dest with Dozer :

DozerBeanMapper mapper = new DozerBeanMapper();

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

Exception in thread "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.

So, why can't Dozer convert Enum to Enum when they are not properties of complex objects?

Dozer cannot map enums because it relies on the existence of the default no-argument public constructor. They can only be mapped when they are part of a larger 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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