Java Generic Parameter Locator
Categories: Java
Here’s a simple snippet of Java code which takes an object which has an ancestor type like interface Base<T,V>
, and returns the actual type of T or V (eg Integer).
Yes, Java’s “type erasure” does introduce a small limitation: the object must have been declared as an instance of some non-generic type, eg new Foo
, not new Foo<String>
. In other words, it doesn’t work for generic type-parameters specified “inline” with the object instantiation. However in many cases this is fine.
My particular use-case for this was as follows:
- a generic base class has type parameter <T>, and defines a protected method
- at runtime, some object whose type descends from that base type calls the inherited method
- the inherited method then needs to know what type T is for the current instance
You can find the code here: