0
我正在嘗試在我的實體和DTO之間進行轉換。Spring BeanUtils無法實例化泛型類
我有我的DTO的基類(稱爲模型):
public class BaseModel<Entity> implements Model<Entity> {
@Override
public Entity toEntity(Class<Entity> entityClass) {
Entity entityInstance = BeanUtils.instantiate(entityClass);
BeanUtils.copyProperties(this, entityInstance);
return entityInstance;
}
}
但是下面的測試不通過:
public class BaseModelTest {
@Entity
public class SomeEntity {
@Id
private Long id;
private String name;
public SomeEntity() {
}
public SomeEntity(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
@Test
public void toEntity_givenEntityClass_shouldCreateNewInstance() throws Exception {
//given
BaseModel<SomeEntity> model = new BaseModel();
//when
SomeEntity entity = model.toEntity(SomeEntity.class);
//then
assertNotNull(entity);
}
}
我得到異常:(儘管事實上,在調試器下我查看所有構建函數):
org.springframework.beans.BeanInstantiationException: Failed to instantiate [package.BaseModelTest$SomeEntity]: Is it an abstract class?; nested exception is java.lang.InstantiationException: package.BaseModelTest$SomeEntity
Caused by: java.lang.InstantiationException: package.BaseModelTest$SomeEntity
Caused by: java.lang.NoSuchMethodException: package.BaseModelTest$SomeEntity.<init>()
非常感謝你!這是一個內部類問題。如果內部模型類被「普通」類替換,它也可以工作 –
是的,把'SomeEntity'放入'SomeEntity.java'中也解決了這個問題。 –
@BTW我不想將JPA與JSR-303或Jackson註釋混合在一起。 –