Alex Rivera | Logout

Java Generics with Class <T>

Asked 2009-05-31T14:04:26.673
9

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

Edit
Report

1 Answer

4

You have to genericize your references to Class. For example:

Class<Integer> type = Integer.class
Integer i = verifyType("100",type);

would work fine.

As would:

Map<String, Class<?>> format = new HashMap<String, Class<?>>();

However, this will never work:

Integer i = verifyType("100",format.get("Vendor Number"));

Because format is not defined as:

Map<String, Class<Integer>>

If it was, the casting would work, but the design would be pointless.

The closest you can get is:

Integer i = verifyType("100",(Class<Integer>) format.get("Vendor Number"));

However, you will get a compiler warning doing it, as you must - it is an inherently unsafe cast. The compiler is taking your word for it that that format.get statement will return an integer. If you are sure of that, then that is what unsafe casts are for. If you want to get rid of the compiler warning, you could do this:

    Class<?> type = format.get("Vendor Number");
    Integer i = null;
    if (type == Integer.class) {
        i = verifyType("100", Integer.class);
    } else {
        //What do you want to do?
    }
answered 2009-05-31T14:52:54.827

Your Answer