开发者

Java generics infering type

my IDE generates a warning when i use the following code:

aMethod(List.class);

"Type safety: The expression of type List needs unchecked conversion to conform to ..." Sadly when i try to let the IDE fix it, it doesn't work. What is the proper syntax to infere the generic type ? Thx in advance for any help.

edit:

Signature of the method:

public static <T> T aMethod(Class<T> clazz)  

Lets make it simple and say the type i wanna refere to is 开发者_JAVA百科String.

kuku


If You want only to remove the waring from the code:

aMethod(Class<?> clazz);

For classes that inherit the Collection class You can use something this:

public <T extends Collection<?>> void clazz(Class<T> clazz);


List.class is what is known as a raw type.

Generics use type erasure to remove the parametrized types from the compiled code. The typesafe checks are done solely at compile time. It's the compiler which make sure you only add Strings to a List.

At runtime, the String is gone, and your List<String> functions exactly as a pre-generics List would. So you are passing it to a method which is trying to guess what the T is in List<T>. But it will never be able to determine this, since the information will be gone.

Since the types can't be matched, the compiler is warning you that your code may allow non-typesafe access to your list. That is, since List<String> and List<Integer> are treated the same at runtime, and are both represented by List.class, you might be setting yourself up for a situation where at runtime, your code might attempt to add a String to a List<Integer> which will fail.

See Also

Generics in the JLS

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜