java泛型类继承问题?

如题所示,想通过继承GeoResult类来扩展属性

   //GeoResult 类

public class GeoResult<T> implements Serializable {

private static final long serialVersionUID = 1637452570977581370L;

private final T content; private final Distance distance;

public GeoResult(T content, Distance distance) {

Assert.notNull(content, "Content must not be null!");

Assert.notNull(distance, "Distance must not be null!");

this.content = content;

this.distance = distance;

}

}

//扩展GeoResult类

public class GeoExtendResult<T> extends GeoResult<T> implements Serializable{

public GeoExtendResult(T content, Distance distance) {

super(content, distance);

}

}

//这是正确的

List<GeoResult<RedisGeoCommands.GeoLocation<String>>> geoResultList = radiusGeo.getContent();

//报类型不匹配

List<GeoExtendResult<RedisGeoCommands.GeoLocation<String>>> geoResultList = radiusGeo.getContent();

图片描述

回答:

我倒是看懂了你想做什么,但你这问题描述的有点问题。泛型的特点是泛,给你举个例子吧
针对泛型接口:

GeoExtendResult extends GeoResult<?> //不限定泛型类型

GeoExtendResult extends GeoResult<RedisDemo.GeoList<String> // 限定泛型类型为RedisDemo.GeoList<String>

泛型类:

GeoExtResult<T> extends GeoResult<T> //子类也想用泛型必须添加泛型

第三次更新:

public class GenericT<T> implements Serializable {

private static final long serialVersionUID = 1637452570977581370L;

private final T content;

private final String distance;

public GenericT(T content, String distance) {

this.content = content;

this.distance = distance;

}

}

public class GenericExtT<T> extends GenericT<T> {

public GenericExtT(T content, String distance) {

super(content, distance);

}

public List<GenericExtT<T>> getContent() {

return Collections.unmodifiableList(Lists.newArrayList());

}

@Autowired GenericExtT genericExtT;

public void main(String[] args){

//这是正确的

List<GenericExtT<? extends T>> geoResultList = genericExtT.getContent();

}

}

以上是 java泛型类继承问题? 的全部内容, 来源链接: utcz.com/p/178820.html

回到顶部