Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Guava's TypeToken<T>.getRawType() return Class<? super T> instead of Class<T>

From Effective Java Second Edition, Item 28 : "Do not use wildcard types as return types. Rather than providing additional flexibility for your users it would force them to use wildcard types in client code."

public final Class<? super T> getRawType()

I've just been getting to grips with generic wildcards to understand the last unchecked cast warning I have in a piece of code I am writing and I don't understand why getRawType() returns a wildcard type.

class Base<T>{}
class Child<T> extends Base<T>{}

public <C> void test (TypeToken<? extends Base<C>> token) {
    Class<? extends Base<C>> rawType = (Class<? extends Base<C>>) token.getRawType();
}

I have to cast token.getRawType() as it returns a

Class<? super ? extends Base<C>>
like image 240
MikeB Avatar asked Jun 29 '12 12:06

MikeB


1 Answers

What if you have a TypeToken<ArrayList<String>> and you want to get Class<ArrayList> (that is the raw type). If it returned Class<T>, then it would return Class<ArrayList<String>> which is not Class<ArrayList> that you want.

like image 145
newacct Avatar answered Oct 07 '22 00:10

newacct