josh
josh

Reputation: 11

How to determine the declared type of a generic object at runtime?

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.

Upvotes: 1

Views: 241

Answers (5)

Nirmal- thInk beYond
Nirmal- thInk beYond

Reputation: 12054

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());
    }

Upvotes: 0

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.

Upvotes: 2

Michael Borgwardt
Michael Borgwardt

Reputation: 346317

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.

Upvotes: 0

kan
kan

Reputation: 28951

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

Upvotes: 3

hvgotcodes
hvgotcodes

Reputation: 120198

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

Upvotes: 2

Related Questions