gpt4 book ai didi

具有扩展类型的 Java 泛型转换

转载 作者:行者123 更新时间:2023-11-29 04:59:15 25 4
gpt4 key购买 nike

我想转换一个泛型类型,将类“BoostItem”扩展到它的基类“BoostItem”,然后调用它的构造函数(使用整数)。我怎样才能做到这一点? T 必须始终扩展 BoostItem,因此应该始终可以将 Argument boostFood 转换为类 BoostItem,对吧?我在这里错过了什么......?

public <T extends BoostItem> void addBoostFood(Class<T> boostFood){
try {
// How to cast boostFood to BoostItem
// Call constructor of BoostItem with Parameter int
((BoostItem)boostFood).newInstance(5); //Doesnt work


} catch (Exception e){
e.printStackTrace();
}
}

------------ 编辑生成的源代码(看起来很丑,我不认为我会使用它,因为它太慢且不灵活)

  public <T extends BoostItem> void addBoostFood(Class<T> boostFood){
try {
Constructor[] ctors = boostFood.getDeclaredConstructors();
for(Constructor c : ctors) {
Type[] types = c.getGenericParameterTypes();
boolean isRightCon = true;
for(Type t : types){
if(t != Integer.class)
isRightCon = false;
}
if(isRightCon)
gFoodBoosterList.add((BoostItem) c.newInstance(new Integer(5)));
}
}catch (Exception e){
e.printStackTrace();
}
}

最佳答案

您试图将 Class 对象 boostFood 转换为 BoostItem 对象,而不是调用 newInstance.

首先,您可以将强制转换移到括号外,以便强制转换方法调用的结果。但这应该是不必要的,因为您始终可以将子类对象分配给父类(super class)引用。

二、newInstance method in Class不接受任何参数。这是包含无参数构造函数的类的便捷方法。您需要通过 getDeclaredConstructorClass 获取适当的 Constructor 对象,将 int.class 作为参数类型(或 Integer.class 视情况而定)。然后你可以调用Constructor's newInstance method ,它确实接受参数。

关于具有扩展类型的 Java 泛型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32619760/

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