How to get the actual type arguments to an indirectly implemented generic interface?

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 { }
class Base implements Awesome> { }
class Child extends Base> { }

class AwesomeExample {      
    public static void main(String[] args) {
        Awesome>> x = new Child();

        System.out.println(
            ((ParameterizedType)
                Child.class.getGenericSuperclass()
            ).getActualTypeArguments()[0]
        );
        // prints "java.util.List"

        System.out.println(
            ((ParameterizedType)
                Base.class.getGenericInterfaces()[0]
            ).getActualTypeArguments()[0]
        );
        // prints "java.util.Set"        

        investigate(x);
        // we want this to print "Set>"
    }

    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>
  • Base implements Awesome>

And therefore we can put all the bits and pieces together to conclude that:

  • Child implements Awesome>>

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?

7
задан polygenelubricants 23 December 2010 в 08:08
поделиться