Reputation: 170723
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?
Upvotes: 5
Views: 800
Reputation: 420951
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.)
Upvotes: 6
Reputation: 147154
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.
Upvotes: 2
Reputation: 114767
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.
Upvotes: 0