Close

Java Reflection - Class.getGenericSuperclass() Examples

Java Reflection Java Java API 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public Type getGenericSuperclass()

Returns the Type representing the superclass of this class, interface, primitive type or void. If the superclass is a parameterized type, the Type object reflects the actual type parameters.

Returns:
the superclass of the class represented by this object

Examples


package com.logicbig.example.clazz;

import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;

public class GetGenericSuperclassExample {

public static void main(String... args) {
Class<MyClass> c = MyClass.class;
Type genericSuperclass = c.getGenericSuperclass();
printType(genericSuperclass);
}

private static void printType(Type type) {
if (type instanceof Class) {
System.out.println("type is Class");
System.out.println("class name: " + ((Class) type).getSimpleName());
} else if (type instanceof ParameterizedType) {
System.out.println("type is ParameterizedType");
Type[] aType = ((ParameterizedType) type).getActualTypeArguments();
System.out.println("printing each one of ActualTypeArguments:");
System.out.println("----");
for (Type type1 : aType) {
printType(type1);
}
System.out.println("----");
} else if (type instanceof TypeVariable) {
System.out.println("type is TypeVariable");
String typeVariableName = ((TypeVariable) type).getName();
System.out.println("typeVariableName: " + typeVariableName);

} else if (type instanceof GenericArrayType) {
System.out.println("type is GenericArrayType");
Type genericComponentType =
((GenericArrayType) type).getGenericComponentType();
printType(genericComponentType);
}
}

private static class MyClass extends MySuperClass<String, Integer> {}

private static class MySuperClass<T, R> {}
}

Output

type is ParameterizedType
printing each one of ActualTypeArguments:
----
type is Class
class name: String
type is Class
class name: Integer
----




See Also