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

标签 java generics casting extends

我想转换一个泛型类型,将类“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/

相关文章:

c# - 检查变量是否为 double 据类型

java - BufferedInputStream 标记/重置无效标记

ruby-on-rails - 使用 STI 时如何将 ActiveRecord 对象转换为另一个类?

java - 网络上单台机器的多套接字客户端

generics - 泛型在 Gosu 中是如何工作的?

c# - 创建一个 IList<T> 的 Item<U>?

generics - 具有高阶功能的异常处理/抑制

c - 如何在 C 中将 uint8_t* 分配给 uint16_t

java - 无法理解 Java 中的递归

java - 如何在 spring boot 属性文件中使用时间戳?