views:

49

answers:

2

I have the following problem:

Given a Guice type literal TypeLiteral<T> template and a class Class c implementing or extending T, construct a type Type t which is equivalent to c with all type variables instantiated so as to be compatible with template.

If c has no type variables, it's easy; c is the type in question. However, if c has type variables, then I need to do the following:

  1. Find the type in c's inheritance and implementation hierarchy corresponding to the raw type of T
  2. Walk through the type parameter structure, finding any type variable uses and their corresponding types in template
  3. Use the Guice Types helper functions to create a type from c instantiated with the types found in (2).

Of course, there are error cases and it might not be complete. If it can't find matching uses of all type variables, it will fail. There might be other cases as well. However, if I have this:

class CS<I> implements S<Map<I,Float>> {
    // some stuff
}

and a type literal TypeLiteral<S<Map<I,Float>>>, I want to get a type which represents CS fully instantiated to match the type literal.

It looks like reflection provides enough information to accomplish this, but the logic looks complex and error-prone. Is there an existing library which exposes this logic?

A: 

TypeLiteral.getSupertype() should do the trick:

TypeLiteral<?> t = TypeLiteral.get(x).getSupertype(y);
Jesse Wilson
I tried `template.getSupertype(c)`, but it complains that `c` is not a supertype of `T` (which is true, as it is a subtype of `T`).
Michael E
A: 

This problem is an instance of the unification problem, and as such the standard unification algorithm is applicable and not as complicated as I initially thought. Further, this instance of the problem allows for some significant simplifying assumptions, as one of the trees will contain no variables. 200 lines of Java later, I have a working solution.

Michael E