我正在尝试实现在我的实体和DTO之间进行转换的内容。
我的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);
}
}
我有例外:(尽管事实上,在调试器下我看到所有的ctors):
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>()
答案 0 :(得分:2)
目前,要创建新的SomeEntity
实例,您需要一个封闭的BaseModelTest
类的实例。 SomeEntity
应该是一个内部静态类。替换:
public class SomeEntity {
与
public static class SomeEntity {
顺便说一句。如果将DTO类映射到模型类,则没有任何意义,它不会添加任何值,它只是样板代码。