How can you determine what type of object a generic is using at runtime ?
4 Answers
Due to type erasure, you cannot determine the actual type parameter(s) of a generic object instance. The best you can do is set things up so you can pass a class object to code that needs to know the actual type. For example, this is what java.util.EnumMap
does in one of its constructor.

- 232,168
- 48
- 399
- 521
If you mean the T
in List<T>
(for instance), you can't, because Java uses type erasure. At runtime, a List<T>
just looks like a List
. This is true except in the edge case of anonymous classes, where it's possible if you jump through hoops to find the parameter type. But in the general case, you cannot. You usually have to communicate that information separately.

- 1,031,962
- 187
- 1,923
- 1,875
It is not possible to get the object type of "Generics" at run time. If we use object.getclass(), so we can get object of any class with the class name.

- 463
- 5
- 14
First we explain What is Generic
Generic in Java is one of important feature added in Java 5,
From Oracle's documentation:
Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:
Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
Insert type casts if necessary to preserve type safety.
- Generate bridge methods to preserve polymorphism in extended generic types.
Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.
Now how to make possible to get the generic type on runtime, with the help of this link
read: http://www.west-wind.com/weblog/posts/2011/Nov/11/Dynamically-creating-a-Generic-Type-at-Runtime

- 170,088
- 45
- 397
- 571

- 586
- 1
- 6
- 15