简体   繁体   中英

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>>(){})

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> is unknown in the method body, this type might be an instance of List<SomeClass> or not. The compiler can't know for sure and prevents the returning of a 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM