【问题标题】:Returning child type generic to parent type generic in java在java中将子类型泛型返回到父类型泛型
【发布时间】:2022-10-14 14:26:56
【问题描述】:

我经历了很多与此相关的问题,但我无法解决我的问题。 我的问题如下。

我有一个父抽象类。

public class abstract Parent{ }

我还有另外两个从上述父类扩展的子类。

public class ChildOne extends Parent{}
public class ChildTwo extends Paretn{}

在另一个类中,我正在使用这三个类,如下所示。

public class A{ 
   public List<ExcelRecord<Parent>> getExcelRecords(){
      ChildOne childone = new ChildOne();
      List<ExcelRecord<ChildOne>> list = new ArrayList();
      //few logics

      return list; //**compilation here**
   }
}

编译问题是: 必需:列表<ExcelRecord> 提供:ist<ExcelRecord>

我需要将子类型泛型返回到父类型泛型。我怎样才能做到这一点?

【问题讨论】:

    标签: java generics


    【解决方案1】:

    在返回类型中使用通配符。此通配符将接受任何扩展父类的类

    
    public List<ExcelRecord<? extends Parent>> getExcelRecords() {
       //...
    }
    
    

    请随时查看Java Generics FAQ 了解更多详情

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2011-05-11
      相关资源
      最近更新 更多