Generic class literals - e.g,, Class<Map<String, Integer>>.class

Generic class literals - e.g,, Class<Map<String, Integer>>.class

Post by Purus » Wed, 13 Apr 2005 21:32:40


Hi,

Let us say, I have a static method as follows:

static <T> getData(Class<T> cls, String name) {
...
return cls.cast(..);
}

I would like to call the above method like:

Map<String, Integer> data = getData(Class<Map<String, Integer>>,
"name")

or

Map<String, Integer> data = getData(Map<String, Integer>.class,
"name")

and avoid all compiler warnings. But, the compiler does not accept
both.

Did any one run into this and know of a way to get this working?

Thanks
Purush
 
 
 

Generic class literals - e.g,, Class<Map<String, Integer>>.class

Post by Lasse Reic » Thu, 14 Apr 2005 04:16:57

"Purush" < XXXX@XXXXX.COM > writes:


Should have a return type:
static <T> T getData(Class<T> cls, String name) {


Here "Class<Map<String,Integer>>" is not a valid expression.


Here "Map<String,Integer>.class" is not working, because
"Map<String,Integer>" is not a class. It is a type, but not a class.
If it should be any value (at runtime, mind you), it would be
"Map.class", but that would go for "Map<Integer,Boolean>" as well.

A class object exists only at runtime, and there are no generics left
at that time, so "Map<String,Integer>.class" does not make sense.


I guess your best bet would be an unchecked warning:

Map<String, Integer> data = getData(Map.class, "name");

/L
--
Lasse Reichstein Nielsen - XXXX@XXXXX.COM
DHTML Death Colors: <URL: http://www.yqcomputer.com/ ;
'Faith without judgement merely degrades the spirit divine.'

 
 
 

Generic class literals - e.g,, Class<Map<String, Integer>>.class

Post by Purush Rud » Thu, 14 Apr 2005 10:15:31

If I create a dummy interface like:

interface MapStringInteger extends Map<String, Integer> {
// empty marker interface
}

and change the call to:

Map<String, Integer> data = getData(MapStringInteger.class, "name");

the compiler seems to accept it without unchecked warnings. But, I am
looking for a cleaner solution.

Thanks
Purush
 
 
 

Generic class literals - e.g,, Class<Map<String, Integer>>.class

Post by P.Hil » Fri, 15 Apr 2005 03:55:58


> But, I am looking for a cleaner solution.

Why do you say defining a named interface is less clean?

-Paul
 
 
 

Generic class literals - e.g,, Class<Map<String, Integer>>.class

Post by Purush Rud » Fri, 15 Apr 2005 05:40:26

Because I have no further use for this interface other than avoiding
this unchecked exception. So, either I need to define this as a public
interface for all clients to use, or they need to create their own
versions of this interface.

If I use the named interface in method signature, I can not call
getData() method with Map<String, Integer> values returned from other
method calls.