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

Dan*_*lan 3 java generics

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

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

构造函数:

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

错误:

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
Run Code Online (Sandbox Code Playgroud)

为什么我收到此错误?我如何解决它?我不想改变构造函数来接受GenericType<List<FamilyHistoryPersonModel>> listResultGenericType

我使用的是JDK 1.6

rge*_*man 5

正如a List<Dog>不是List<Animal>偶数Animal子类Dog,a GenericType<List<FamilyHistoryPersonModel>>不是a GenericType<List<? extends PersonModel>>,即使a List<FamilyHistoryPersonModel>是a List<? extends PersonModel>.

解决方案是在顶级泛型类型参数中提供通配符.在MapValue构造函数中,更改参数

GenericType<List<? extends PersonModel>> listResultGenericType
Run Code Online (Sandbox Code Playgroud)

GenericType<? extends List<? extends PersonModel>> listResultGenericType
Run Code Online (Sandbox Code Playgroud)

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

  • @tieTYT Java泛型类型是不变的,你期望它们是协变的.有关详细信息,请参阅[List List <Dog> List <Animal>的子类?为什么Java的泛型不是隐式多态的?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p). (3认同)