Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of a generic declaration programmatically?

I declare a class as follows:

public class SomeClass extends AdditionalClass<GenericClass> {
  ...
}

This...

SomeClass object = new SomeClass();
System.out.println(object.getSuperClass().getSimpleName());

...yields "AdditionalClass". What method call or calls would allow me to interrogate that object and get "GenericClass" as a result?

like image 783
IVR Avenger Avatar asked Jul 21 '15 14:07

IVR Avenger


1 Answers

You have to fetch the array of ParameterizedType(s) of the superclass. For example:

SomeClass object = new SomeClass();
Type parameterizedClassType = 
         ((ParameterizedType) object.getClass().getGenericSuperclass())
         .getActualTypeArguments()[0];
System.out.println(parameterizedClassType.getTypeName());

This should print com.whateverpackage.GenericClass.

Note that even type erasure occurs when SomeClass is compiled, the type parameters information about the superclass(es) is preserved, because they are part of the definition of the class.

However, if SomeClass was a generic one (i.e. was something like SomeClass<X> extends AdditionalClass<GenericClass>), then for all the SomeClass instances the type-parameter (i.e. <X>) would have been replaced with some actual type, which would not have been part of the .getActualTypeParameters() array.

like image 138
Konstantin Yovkov Avatar answered Oct 11 '22 23:10

Konstantin Yovkov