1
HashMap<String, Boolean> myMap = new HashMap<String, Boolean>(); 
System.out.println(func1(myMap)); //should print "HashMap<String, Boolean>"

I want to know is there such a function. This function should take an object and return the exact type of the object. It should work with all the collections.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
josh
  • 11
  • 1
  • Check out this post http://stackoverflow.com/questions/1942644/get-generic-type-of-java-util-list – Bala R Nov 15 '11 at 13:15
  • possible duplicate of [How to determine the class of a generic type?](http://stackoverflow.com/questions/182636/how-to-determine-the-class-of-a-generic-type) – Björn Pollex Nov 15 '11 at 13:17

5 Answers5

3

It's impossible, this information is not available at run-time. There is a "type erasure" in Java. http://download.oracle.com/javase/1,5.0/docs/guide/language/generics.html

kan
  • 28,279
  • 7
  • 71
  • 101
2

Generics information is erased at runtime. println runs at runtime. At runtime the map is just a HashMap.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
2

Unfortunately, no.
You can find that it is a HashMap using reflection, but you will not be able to find the type parameters due to type erasure.

From Wikipedia:

Generics are checked at compile-time for type-correctness. The generic type information is then removed in a process called type erasure. For example, List<Integer> will be converted to the non-generic type List, which can contain arbitrary objects. The compile-time check guarantees that the resulting code is type-correct.

As a result of type erasure, type parameters cannot be determined at run-time.

Community
  • 1
  • 1
0

This is completely impossible due to type erasure. At runtime, the type parameters of objects are erased and only exist as casts at the point they're used. The type parameters of fields and methods can be retrieved via reflection, if they're concrete.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
0

It may possible using one trick if map have at least one entry as below

    Map<String, Boolean> map = new HashMap<String, Boolean>();
    System.out.println(map.getClass().getName());
    Set set = map.entrySet();
    for (Object object : set) {
        Map.Entry e = (Entry) object;
        System.out.println(e.getKey().getClass());
        System.out.println(e.getValue().getClass());
    }
Nirmal- thInk beYond
  • 11,847
  • 8
  • 35
  • 46