I have a parameterized interface that is implemented in many different ways. At run time I need to figure out, given an arbitrary object that implements that interface, what the actual type parameters to the interface is.
Here's a snippet to illustrate the problem, and a halfway attempt to solve it (also on ideone.com):
import java.util.*;
import java.lang.reflect.*;
interface Awesome<X> { }
class Base<E> implements Awesome<Set<E>> { }
class Child extends Base<List<Integer>> { }
class AwesomeExample {
public static void main(String[] args) {
Awesome<Set<List<Integer>>> x = new Child();
System.out.println(
((ParameterizedType)
Child.class.getGenericSuperclass()
).getActualTypeArguments()[0]
);
// prints "java.util.List<java.lang.Integer>"
System.out.println(
((ParameterizedType)
Base.class.getGenericInterfaces()[0]
).getActualTypeArguments()[0]
);
// prints "java.util.Set<E>"
investigate(x);
// we want this to print "Set<List<Integer>>"
}
static void investigate(Awesome<?> somethingAwesome) {
// how to do this?
}
}
It looks like there's enough generic type information at runtime to deduce that:
Child extends Base<List<Integer>>
Base<E> implements Awesome<Set<E>>
And therefore we can put all the bits and pieces together to conclude that:
Child implements Awesome<Set<List<Integer>>>
So it looks like the problem is solvable, but it's not that simple, since we'd have to work with an arbitrary class/interface hierarchy. Is this the only way to do this? Is there a simpler way? Has someone written a library to do this already?