Java Reflection - Class.getGenericInterfaces() Examples

Code Snippets Java Reflection Java 


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[] getGenericInterfaces()

Returns the Type array representing the interfaces directly implemented by this class or interface.

If a superinterface is a parameterized type, the Type object returned reflects the actual type parameters.

Returns:
an array of interfaces implemented by this class

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;
import java.math.BigInteger;

public class GetGenericInterfacesExample {

public static void main(String... args) {
Class<MyClass> c = MyClass.class;
Type[] genericInterfaces = c.getGenericInterfaces();
for (Type genericInterface : genericInterfaces) {
System.out.println(genericInterface);
printType(genericInterface);
}
}

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 implements MyInterface<String, BigInteger> {}

private static interface MyInterface<T, R> {}
}

Output

com.logicbig.example.clazz.GetGenericInterfacesExample$MyInterface<java.lang.String, java.math.BigInteger>
type is ParameterizedType
printing each one of ActualTypeArguments:
----
type is Class
class name: String
type is Class
class name: BigInteger
----




See Also