我有一个这样的枚举:
public static enum TestEnum {
// main
ENUM_A (1,"test1",TestADto.class),ENUM_B (2,"test2",TestBDto.class),ENUM_C (3,"test3",TestCDto.class),...
private Class<? extends Dto> dtoClass;
public Class<? extends Dto getDtoClass() {
return dtoClass;
}
...
}
所有这些dto类都扩展了相同的抽象(dto)类:
public abstract class AbstractDto {
private String foo;
private int bar;
...
AbstractDto(AbstractClassNeededForInitialization o) {
this.foo = o.getFoo();
this.bar = o.getBar();
}
... some functions here ...
}
这将是TestADto的示例Dto实现:
@Getter
@Setter
public class TestADto extends AbstractDto {
private String anotherFoo;
private int anotherBar;
...
public TestADto(AbstractClassNeededForInitialization o) {
super(o);
}
... some functions here ...
}
是否有可能(即使用Java 8)在枚举引用类中创建这些的具体实例,而不需要知道它具体是什么?
让我说在一个函数中的某个点,即时通讯具有Enum_A.现在我想创建一个dto实例(TestADto.class).对此最好的方法或模式是什么?
想象一个包含100多个条目的枚举,每个条目都有不同的dto,它扩展了相同的抽象dto或实现了一个接口.
如何在不编写大量if else或switch语句的情况下创建这些具体对象,或者逐个处理它.
我读了一些关于反射和代理的东西,但不确定这是否是正确的方式.或者目前的状态是否已经有了一种糟糕的设计?
我想要达到的一切是将dto名称分配给枚举,以便稍后在某些特定点创建它.但如果可能的话,不要创造巨大的条件……
@编辑
我忘了提到创建每个dto的实例需要有传递给构造函数的对象.传递给构造函数的此对象也实现了一个接口.
解决方法
如果需要为DTO子类调用空构造函数,可以在存储在字段中的枚举构造函数中提供supplier:
...
ENUM_A (1,TestADto::new),TestBDto::new),TestCDto::new);
private supplier<Dto> supplierDto;
TestEnum(int i,String name,supplier<Dto> supplierDTO){
this.supplierDto = supplierDTO;
...
}
...
然后,您可以通过调用supplierDto.get()来创建Dto实例;
编辑后:
I forgot to mention that creating a instance of each dto needs to have
object which is passed to the constructor.
供应商< Dto>不再适合,因为它不是设计用于提供一个参数的构造函数.
假设您的构造函数是这样的:
public class TestADto{
...
private MyInterface myInterface;
public TestADto (MyInterface myInterface){
this.myInterface = myInterface;
}
...
}
你可以在枚举构造函数中声明一个Function< MyInterface,Dto>与此构造函数匹配的参数.
...
ENUM_A (1,TestCDto::new);
private Function <MyInterface,Dto> dtoConstructor;
TestEnum(int i,Function <MyInterface,Dto> dtoConstructor){
this.dtoConstructor = dtoConstructor;
...
}
public Dto createInstance(MyInterface myInterface){
return myInterfacetoDtoFunction.apply(myInterface);
}
...