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:
Class type = Integer.class
Integer i = verifyType("100",type);
to
Class<Integer> type = Integer.class
Integer i = verifyType("100",type);
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:
Map<String, Class> format = new HashMap<String, Class>();
format.put("Vendor Number", Integer.class);
format.put("Vendor Dispatch", Date.class);
Integer i = verifyType("100",format.get("Vendor Number"));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With