Possible Duplicate:
Get generic type of java.util.List
I have a Map and I want to get the type of T from an instance of that Map. How can I do that?
e.g. I want to do something like:
Map<String, Double> map = new HashMap<String, Double>();
...
String vtype = map.getValueType().getClass().getName(); //I want to get Double here
Of course there's no such 'getValueType()' function in the API.
Map does not supports duplicate keys. you can use collection as value against same key. Because if the map previously contained a mapping for the key, the old value is replaced by the specified value.
Map Values() method returns the Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. Parameter: This method does not take any parameter.
You can't insert duplicate keys in map but you can insert duplicate values with keys different.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With