java – 创建新的实例类引用
|
我有一个这样的枚举: 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子类调用空构造函数,可以在存储在字段中的枚举构造函数中提供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实例; 编辑后:
供应商< 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);
}
... (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
