gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:05:56 24 4
gpt4 key购买 nike

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

公共(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com