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

Java Generics Casting with extended Type

我想转换一个泛型类型,将 class 'BoostItem' 扩展到它的基础 class 'BoostItem',然后调用它的构造函数(使用整数)。我怎样才能做到这一点? T 必须始终扩展 BoostItem,因此应该始终可以将 Argument boostFood 转换为 class 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.

的结果

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

其次,newInstance method in Class doesn't take any arguments. This is a convenience method for class that contain no-argument constructors. You will need to get the appropriate Constructor object from the Class via getDeclaredConstructor, passing in int.class as the parameter type (or Integer.class as the case may be). Then you can call Constructor's newInstance method,它确实带有参数。