samedi 2 juillet 2016

Get generic parameters of a generic type

For some background, I'm working on some framework stuff for a programming language I'm developing (JVM language, that is), and was testing some of the framework with Java classes, hence all the weird wrappers below.


So, my questions is, how do I get the type variables of a type parameter's bounds? Currently I have the following:

public static TemplateGenerics of(Class clazz) {
    TemplateGenerics generics = new TemplateGenerics(); //TemplateGenerics is a wrapper class for generics that appear in the class header
    Stream.of(clazz.getTypeParameters()).forEach(typeVariable -> {
        java.lang.reflect.Type b = typeVariable.getBounds()[0];
        try {
            Class c = Primitives.resolveClass(b.getTypeName().split("<", 2)[0]); //Is there a better way to do this?
            TemplateGenerics sub = TemplateGenerics.of(c); //Recursivley get the generics - it fails here
            generics.getConditionals().add(new Conditional(new Type.Hierarchical(sub, c.getName()), Conditional.Condition.EXTENDS, typeVariable.getName())); //Conditional is another wrapper class that handles bounds of the generic, 
                                                                                                                                                             //Type.Hierachical is yet another wrapper class that wraps types that appear in class headers
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e); //For testing purposes
        }
    });
    return generics;
}

But this fails with a StackOverflowException when it encounters something like this:

public class A<T extends A<T>> ...

Since it just continues trying to get the type parameters of A over and over. I've been unable to find a method of getting the type variable's type variables... I've tried messing around with getGenericDeclaration, but it does not seem to return what I need. Any help is greatly appreciated.





Aucun commentaire:

Enregistrer un commentaire