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

P

Purush

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
 
L

Lasse Reichstein Nielsen

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

static <T> getData(Class<T> cls, String name) {

Should have a return type:
static said:
...
return cls.cast(..);
}

I would like to call the above method like:

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

Here "Class said:
Map<String, Integer> data = getData(Map<String, Integer>.class,
"name")

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 said:
and avoid all compiler warnings. But, the compiler does not accept
both.

I guess your best bet would be an unchecked warning:

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

/L
 
P

Purush Rudrakshala

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
 
P

Purush Rudrakshala

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,113
Latest member
Vinay KumarNevatia
Top