Andy Andy - 3 months ago 10
Java Question

Retrieving type parameters from an instance of a generic base interface

Given 2 interfaces:

public interface BaseInterface<T> { }
public interface ExtendedInterface<T0, T1> extends BaseInterface<T0> {}


and a concrete class:

public class MyClass implements ExtendedInterface<String, Object> { }


How do I find out the type parameter passed to the BaseInterface interface?

(I can retrieve the ExtendedInterface type parameters by calling something like

MyClass.class.getGenericInterfaces()[0].getActualTypeArguments()


but I can't spot an easy way to recurse into any base generic interfaces and get anything meaningful back).

Answer

This problem is not easy to fully solve in general. For example, you also have to take type parameters of the containing class into account if it's an inner class,...

Because reflection over generic types is so hard using just what Java itself provides, I wrote a library that does the hard work: gentyref. See http://code.google.com/p/gentyref/ For your example, using gentyref, you can do:

Type myType = MyClass.class;

// get the parameterized type, recursively resolving type parameters
Type baseType = GenericTypeReflector.getExactSuperType(myType, BaseInterface.class);

if (baseType instanceof Class<?>) {
	// raw class, type parameters not known
	// ...
} else {
	ParameterizedType pBaseType = (ParameterizedType)baseType;
	assert pBaseType.getRawType() == BaseInterface.class; // always true
	Type typeParameterForBaseInterface = pBaseType.getActualTypeArguments()[0];
	System.out.println(typeParameterForBaseInterface);
}
Comments