midnight
midnight

Reputation: 3412

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?

Upvotes: 0

Views: 92

Answers (2)

dcernahoschi
dcernahoschi

Reputation: 15230

Not sure what's wrong here. Any suggestions?

The type <? 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.

Upvotes: 1

sp00m
sp00m

Reputation: 48807

Maybe you could try with the following method signature:

protected <E> E retrieveData(TypeReference<E> ref)

Upvotes: 3

Related Questions