So I have a map:
Map<String, Class> format = new HashMap<String, Class>();
And I would add elements to it like this:
format.put("Vendor Number", Integer.class);
format.put("Vendor Dispatch", Date.class);
....
I have a generic method as follows:
public static <T> T verifyType(String name, Class<T> type) {
if (type == Integer.class) {
return type.cast(new Integer(Integer.parseInt(name)));
}
......
return null;
}
Now this piece of code works great with no compiler issues:
Integer i = verifyType("100",Integer.class);
But, when I try this:
Integer i = verifyType("100",format.get("Vendor Number"));
OR
Class type = Integer.class
Integer i = verifyType("100",type);
Compiler shows me this warning:
Type safety: Unchecked invocation verifyType(String,Class) of the generic method verifyType(String, Class)
That leaves me puzzled… please help…
Change:
to
By only declaring the type as ‘Class’, you’re losing the generic parameter and the verifyType() method can’t infer the class, thus the unchecked warning.
This problem:
can’t really be solved due to type erasure. The compiler can’t infer the type based on a generic parameter that is gone by runtime. This is because Java generics are little more than smoke and mirrors for casting.