Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics with Class <T>

Tags:

java

generics

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

like image 779
Jay Avatar asked May 31 '09 14:05

Jay


1 Answers

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.

like image 83
cletus Avatar answered Sep 26 '22 01:09

cletus