无法在 ModelMapper 中实例化目标 [AbstractClass] 错误的实例

Posted

技术标签:

【中文标题】无法在 ModelMapper 中实例化目标 [AbstractClass] 错误的实例【英文标题】:Failed to instantiate instance of destination [AbstractClass] error in ModelMapper 【发布时间】:2022-01-23 00:08:09 【问题描述】:

我有抽象类Room:

@Entity
@DiscriminatorColumn(name = "room_type")
@Data
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Room 
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "room_id", nullable = false, unique = true)
private int roomId;

@Column(name = "name", nullable = false, length = 255)
private String name;

@JsonIgnore
@OneToMany(mappedBy = "room")
private List<Workstation> workstationsList;

我还有一些从Room 扩展的具体类。 在我的Workstation 类中,我与RoomOne to one 关系:

@Entity
@Data
public class Workstation 
@Id
@Column(name = "workstation_id", nullable = false, unique = true)
private int workstationId;

@ManyToOne
@JoinColumn(name = "room_id")
private Room room;

我正在使用ModelMaperWorkstationDTO 映射到Workstation 实体,但我得到Failed to instantiate instance of destination com.entity.Room. Ensure that com.entity.Room has a non-private no-argument constructor. 这可能是因为Room 是抽象类,有没有办法在不删除@ 中的抽象关键字的情况下解决这个问题987654333@实体?

【问题讨论】:

【参考方案1】:

是的。这是因为不能实例化抽象类(也不能实例化接口)。您可以使用转换器,但要实例化一个具体类,您需要知道它的实际类型是什么:

var roomConverter = new Converter<RoomDto, Room>() 
    // inner mapper to avoid any side effects
    private final ModelMapper innerMapper = new ModelMapper();

    @Override
    public Room convert(MappingContext<RoomDto, Room> context) 
        // If your RoomDto had the type as field you could determine the actual type to
        // instantiate, so one of the possible many RoomImpl.
        return innerMapper.map(context.getSource(), RoomImpl.class);
    
;

// Create the type map and register converter
modelMapper.createTypeMap(RoomDto.class, Room.class).setConverter(roomConverter);

现在添加字段,例如:

@Getter
private Class<Room> classOfRoom;

它可以在方法convert(..)中使用来实例化正确的实现。

【讨论】:

以上是关于无法在 ModelMapper 中实例化目标 [AbstractClass] 错误的实例的主要内容,如果未能解决你的问题,请参考以下文章

升级后 Eclipse“无法实例化类 JavaSourceLookupDirector,在分支目标 53 处期望堆栈图帧”

ModelMapper - 无法将 ArrayList 转换为 List

ModelMapper - 无法将 ArrayList 转换为 List

flywaydb:无法实例化 jdbc 驱动程序

Laravel 5.7:构建时目标不可实例化

尽管桥接头工作正常,但无法在 Swift 中实例化 Obj C 类