[英]Generics extends
There's a method: 有一种方法:
protected List<? extends Object> retrieveData(TypeReference<List<? extends Object>> ref)
When I try to apply it: 当我尝试应用它时:
return (List<SomeClass>) retrieveData(new TypeReference<List<SomeClass>>() {});
I get this notification 我收到此通知
The method
retrieveData(TypeReference<List<? extends Object>>)
in the type AbstractJsonService is not applicable for the arguments(new TypeReference<List<SomeClass>>(){})
类型AbstractJsonService的方法
retrieveData(TypeReference<List<? extends Object>>)
不适用于参数(new TypeReference<List<SomeClass>>(){})
Not sure what's wrong here. 不知道这里出了什么问题。 Any suggestions?
有什么建议么?
也许您可以尝试使用以下方法签名:
protected <E> E retrieveData(TypeReference<E> ref)
Not sure what's wrong here. Any suggestions?
The type <? extends Object>
类型
<? extends Object>
<? extends Object>
is unknown in the method body, this type might be an instance of List<SomeClass>
or not. <? extends Object>
在方法主体中是未知的,此类型是否可以是List<SomeClass>
的实例。 The compiler can't know for sure and prevents the returning of a List<SomeClass>
. 编译器无法确定并阻止
List<SomeClass>
的返回。
When using a protected <T> T retrieveData(TypeReference<T> ref)
you have a "fixed" type for T and the compiler knows for sure that the returned type is the same with TypeReference
's type. 使用
protected <T> T retrieveData(TypeReference<T> ref)
具有“固定”类型,并且编译器肯定知道返回的类型与TypeReference
的类型相同。 Beside this the compiler is able to infer the type T to be List<SomeClass>
when calling the method: retrieveData(new TypeReference<List<SomeClass>>)
, no need anymore to do List<SomeClass>
cast. 除此之外,编译器还可以在调用以下方法时将类型T推断为
List<SomeClass>
: retrieveData(new TypeReference<List<SomeClass>>)
,不再需要进行List<SomeClass>
retrieveData(new TypeReference<List<SomeClass>>)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.