tags:

views:

85

answers:

2

hi,

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 String.

kuku

+3  A: 

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);
Vash
+1  A: 

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

Tom Tresansky
You may also want to have a look at the generics chapter in Effective Java SE, which covers *exactly* this issue.
atamanroman
The generic method is from a library i'm using. So do i understand correctly that my only option here is to supress the warning. I thought i could pass the information that my List contains Strings to the method.
kukudas