Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value type of a map in Java? [duplicate]

Tags:

java

generics

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.

like image 203
naumcho Avatar asked Sep 10 '10 19:09

naumcho


People also ask

Can Java map have duplicate values?

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.

What is the return type of values () method in map?

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.

Can we insert duplicate values in map?

You can't insert duplicate keys in map but you can insert duplicate values with keys different.


1 Answers

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.

like image 74
Rob Hruska Avatar answered Oct 12 '22 12:10

Rob Hruska