告诉enum要使用哪个子类类型

时间:2018-06-11 22:52:39

标签: java enums constructor

您好解释我正在尽力向您展示的内容

public class Main {

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添加它们的原因是在实际应用程序中有100个反对添加到数组列表中,当我得到这些对象时,存储有枚举以显示它们是什么类型。这些对象也会定期更改。

1 个答案:

答案 0 :(得分:2)

目前type中的变量Types属于Class<?>类型。此Class对象可以表示任何类对象,该对象不一定在您创建的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