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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With