If your Map
is a declared field, you can do the following:
import java.lang.reflect.*;
import java.util.*;
public class Generic {
private Map<String, Number> map = new HashMap<String, Number>();
public static void main(String[] args) {
try {
ParameterizedType pt = (ParameterizedType)Generic.class.getDeclaredField("map").getGenericType();
for(Type type : pt.getActualTypeArguments()) {
System.out.println(type.toString());
}
} catch(NoSuchFieldException e) {
e.printStackTrace();
}
}
}
The above code will print:
class java.lang.String
class java.lang.Number
However, if you simply have an instance of the Map
, e.g. if it were passed to a method, you cannot get the information at that time:
public static void getType(Map<String, Number> erased) {
// cannot get the generic type information directly off the "erased" parameter here
}
You could grab the method signature (again, using reflection like my example above) to determine the type of erased
, but it doesn't really get you anywhere (see edit below).
Edit:
BalusC's comments below should be noted. You really shouldn't need to do this; you already declared the Map's type, so you're not getting any more information than you already have. See his answer here.