问题描述
有效的Java第二版,第28项:不要使用通配符类型作为返回类型,而是为用户提供额外的灵活性,这将迫使他们在客户端代码中使用通配符类型。
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()
我刚刚掌握了通用通配符来理解上次未经检查的转换警告我在写一段代码,我不明白为什么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();
}
我必须转换token.getRawType(),因为它返回一个
I have to cast token.getRawType() as it returns a
Class<? super ? extends Base<C>>
推荐答案
如果您有 TypeToken< ArrayList< String>>< / code>并且您希望获得
Class< ArrayList>
(即是 )。如果它返回 Class< T>
,那么它将返回 Class< ArrayList< String>> code> Class< ArrayList>
你想要的。
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.
这篇关于为什么Guava的TypeToken< T> .getRawType()返回Class<?超T>而不是Class< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!