ModelMapper - 无法实例化目标实例

ModelMapper - Failed to instantiate instance of destination

我正在使用 mongodb,所以我正在将实体与创建 DTO 的表示层分离(使用 hibernate-validator 注释)。

public abstract class UserDTO {

    private String id;      
    @NotNull
    protected String firstName;
    @NotNull
    protected String lastName;
    protected UserType type;
    protected ContactInfoDTO contact;
    protected List<ResumeDTO> resumes;

    public UserDTO(){}
    //...

我正在尝试从数据库中检索这个具体的 class

public class UserType1DTO extends UserDTO {

    private CompanyDTO company;

    public UserType1DTO(){
        super();
    }

    public UserType1DTO(String firstName, String lastName, ContactInfoDTO contact, CompanyDTO company) {
        super(UserType.type1, firstName, lastName, contact);
        this.company = company;
    }
    /...

像这样:

return mapper.map((UserType1) entity,UserType1DTO.class);

我收到关于无法实例化的错误 ResumeDTO

Failed to instantiate instance of destination *.dto.ResumeDTO. Ensure that *.dto.ResumeDTO has a non-private no-argument constructor.

ResumeDTO 类似于 UserDTO,是一个抽象的 class 并且对于每个用户类型都有具体的 classes。他们都有没有参数的构造函数。 有什么问题?

您正在尝试将具体的 class 映射到抽象的 class,这是行不通的。 您不能将 Abstract Class 用作目的地。为什么?它不能被实例化。所以你必须使用具体的 class

毫无疑问,它不适用于具有抽象 Class 目的地的地图:

mapper.map(entity, AbstractClass.class);
/*Error: java.lang.InstantiationException
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)*/

您必须使用扩展抽象 Class

的具体 class
public class ConcreteClass extends AbstractClass {
       //
}

然后映射到这个具体的class:

mapper.map(entity, ConcreteClass.class);

更多信息:

由于无法实例化抽象 class 它也不会在目标属性中工作。

Github 中存在与此相关的问题:https://github.com/jhalterman/modelmapper/issues/130

当您在 setter 和 getter 中具有原始数据类型或原始 return 类型或参数化构造函数时,会发生此错误

所以这里需要去掉下面的代码

public UserType1DTO(String firstName, String lastName, ContactInfoDTO contact, 
CompanyDTO company) {
    super(UserType.type1, firstName, lastName, contact);
    this.company = company;
}

它将正常工作。

解决我问题的方法是使用 typeMap 并更新 ModelMapper 的版本。请参考以下link:-

Mapping Lists with ModelMapper

使用typeMap还是报同样的错误。然后我将我的 ModelMapper 版本从 2.0.0 更新到 2.3.5,问题就解决了。