加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 创建新的实例类引用

发布时间:2020-12-15 02:56:59 所属栏目: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
我有一个这样的枚举:
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);
}

...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读