I have the following problem:
Given a Guice type literal
TypeLiteral<T> template
and a classClass c
implementing or extendingT
, construct a typeType t
which is equivalent toc
with all type variables instantiated so as to be compatible withtemplate
.
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:
c
's inheritance and implementation hierarchy corresponding to the raw type of T
template
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?
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.