java - 为什么我不能将子项列表传递给接受 List< 的方法?扩展父>?

标签 java generics

我有一个名为 FamilyHistoryPersonModel 的类扩展名为 PersonModel 的类.

    MapValue mapValue = new MapValue("relatives",
            new GenericType<FamilyHistoryPersonModel>() {},
            new GenericType<List<FamilyHistoryPersonModel>>() {}  //error here
    );

构造函数:

    private MapValue(String pluralUrl, GenericType<? extends PersonModel> singleResultGenericType, GenericType<List<? extends PersonModel>> listResultGenericType) {
        this.pluralUrl = pluralUrl;
        this.singleResultGenericType = singleResultGenericType;
        this.listResultGenericType = listResultGenericType;
    }

错误:

cannot find symbol
symbol  : constructor MapValue(java.lang.String,<anonymous com.sun.jersey.api.client.GenericType<com.models.FamilyHistoryPersonModel>>,<anonymous com.sun.jersey.api.client.GenericType<java.util.List<com.models.FamilyHistoryPersonModel>>>)
location: class com.rest.v2.resource.CreatePersonModelIntegrationTest.MapValue

为什么会出现此错误?我如何解决它?我不想更改构造函数以接受 GenericType<List<FamilyHistoryPersonModel>> listResultGenericType

我正在使用 JDK 1.6

最佳答案

就像一个List<Dog>不是 List<Animal>即使Animal子类 Dog , 一个 GenericType<List<FamilyHistoryPersonModel>>不是 GenericType<List<? extends PersonModel>> ,即使是 List<FamilyHistoryPersonModel>List<? extends PersonModel> .

解决方案是在顶级泛型类型参数处提供一个通配符。在MapValue构造函数,改变参数从

GenericType<List<? extends PersonModel>> listResultGenericType

GenericType<? extends List<? extends PersonModel>> listResultGenericType

我假设您还需要更改 this.listResultGenericType 的类型匹配。

关于java - 为什么我不能将子项列表传递给接受 List< 的方法?扩展父>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24875816/

相关文章:

Java 通用返回类型问题

java - 发送 POST 并读取流响应

javascript - 在浏览器中从 selenium 构建器运行 Mocha 测试

java - 如何通过 Fortify 修复 "reveal system data or debugging information by calling println()"

java - 如何实例化一个使用给定 double 值扩展 Number 的泛型类?

vb.net - 为什么我不能将具有类型约束的泛型参数转换为受约束类型?

java - Hibernate 复制问题—— session 真的需要复制吗?

java - 在单个 ListView 中左右对齐

具有泛型和 Xcode 自动完成功能的 Objective-C 方法返回类型

generics - Ada 泛型和汇编代码生成