java - 告诉枚举要使用什么子类类型

标签 java enums constructor

您好,请解释一下我正在尽力向您展示的内容

公共(public)类主要{

public enum Types{
    ONE(One.class),TWO(Two.class),THREE(Three.class);

    Class<?> type;

    private Types(Class<?> type) {
        this.type = type;
    }


}

public class Manager {
    ArrayList<Number> numbers = new ArrayList<>();

    public void Load() {
        //THIS IS WHERE I AM STUCK
        //I know it can be done like this below to add them in to the array with the types
        numbers.add((One) new Number());
        numbers.add((Two) new Number());
        numbers.add((One) new Number());
        numbers.add((Three) new Number());

        //But i want to be able to add them like this.
        numbers.add(Types.ONE.type.newInstance());

    }

    public void Run() {

        if (numbers.isEmpty()) {
            Load();
        }

        for (Number n : numbers) {
            n.call();
        }
    }
}

public class Number {
    public void call() {

    }       
}

public class One extends Number {   
    @Override
    public void call() {
    }
}

public class Two extends Number {   
    @Override
    public void call() {
    }
}

public class Three extends Number { 
    @Override
    public void call() {
    }
}

}

如果您在代码中查找注释,我会尝试将“Number”添加到数组中,但带有子类。

现在这是应用程序中的一个示例,我希望它的对象在构造函数中具有参数。任何人都可以为我指出正确的方向吗?

我不使用 .add 添加它们的原因是在实际应用程序中,有数百个反对添加到数组列表中的反对意见,当我将这些对象存储在枚举中以显示它们是什么类型时。这些元素也会定期更换。

最佳答案

当前变量 typeTypes类型为Class<?> 。这个Class object 可以表示任何类对象,该对象不一定在 Number 中您创建的类层次结构。

newInstance 返回的任何对象可以是任何类型,因此编译器不允许将其发送到 ArrayList<Number>作为参数;它可能不匹配。

type 的类型添加上限:

enum Types{
    ONE(One.class),TWO(Two.class),THREE(Three.class);

    // add ? extends Number here
    Class<? extends Number> type;  

    // add ? extends Number here
    private Types(Class<? extends Number> type) {  
        this.type = type;
    }
}

您仍然需要捕获所有与反射相关的异常:IllegalAccessExceptionInstantiationException .

另请注意,在 Java 9+ 中, Class.newInstance is deprecated ;您应该将该调用替换为

getDeclaredConstructor().newInstance()

这也会抛出 NoSuchMethodExceptionInvocationTargetException .

关于java - 告诉枚举要使用什么子类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50807094/

相关文章:

java - 类型参数不起作用吗?

Java: vector 声明

java - 从列表中删除后,JPA 枚举集未在数据库中更新

java - 如何更新 JPanel 中的 JLabel?

java - 结合 Java 枚举和点语法 (enum.value1.value2)?

c# - 将 C# Ctor 翻译成 Vb.Net 等价物

function - 如何编写一个只接受一个枚举变体作为输入的函数?

java - 给定提供给其构造函数的参数,如何找到枚举值?

带 header 的 C++ 委托(delegate)构造函数

c++ - 该类有多少个构造函数?