tags:

views:

80

answers:

3

In Java, how can I construct a Type object for Map<String, String>?

System.out.println(Map<String, String>.class);

doesn't compile. One workaround I can think of is

Map<String, String> dummy() { throw new Error(); }
Type mapStringString = Class.forName("ThisClass").getMethod("dummy", null).getGenericReturnType();

Is this the correct way?

A: 

Yes it is the correct and the only way to get the generics at runtime. The type is erased ("type erasure"), the Bytecode-Map is actualy an Object-to-Object Map, the generics defintion in the source code are only used by the compiler to assure type safety.

Andreas_D
The original poster is asking for `Type` not `Class`.
Tom Hawtin - tackline
Everything about `Map<String, String>.class` is known at the compile-time, so there is no reason that shouldn't compile.
Alexey Romanov
@Alexey The trouble is `Map<String,String>.class` makes absolutely no sense whatsoever.
Tom Hawtin - tackline
+2  A: 
public class Test {
    public Map<String, String> dummy;
    public static void main(String... args) throws SecurityException, 
                                                   NoSuchFieldException {
        Type mapStringString = Test.class.getField("dummy").getGenericType();
        // ...

Is a slightly less ugly hack..


As Tom Hawtin suggests, you could implement the methods yourself:

Type mapStrStr2 = new ParameterizedType() {
    public Type getRawType() {
        return Map.class;
    }
    public Type getOwnerType() {
        return null;
    }
    public Type[] getActualTypeArguments() {
        return new Type[] { String.class, String.class };
    }
};

returns the same values as the other approach for the methods declared in ParameterizedType. The result of the first approach even .equals this type. (However, this approach does not override toString, equals and so on, so depending on your needs, the first approach might still be better.)

aioobe
declaring dummy static final would be even lesser uglier :)
codymanix
+1  A: 

It's all done with interfaces, so you can construct your own implementation.

However, the easiest way is to use reflection on a dummy class created for the purpose.

Tom Hawtin - tackline