Recently Alex Miller has explored the use of BGGA closures for building dynamic visitors. Such visitor builders, and also Ricky Clarkson's closure-based pattern matcher, could be greatly simplified if we could obtain the parameter types of the closures at runtime. More precisely, given a closure {T => void}, where T is a parameterized type, we are interested in knowing the class of T.
Since Java generics are implemented via erasure, the generic parameter types can easily be lost. Some ways of "manually" reifying the types include:
Since Java generics are implemented via erasure, the generic parameter types can easily be lost. Some ways of "manually" reifying the types include:
- Passing around class literals, e.g., String.class and Integer.class.
- Subclassing a generic class with specified parameter types. The parameter types can then be read off using getGenericSuperclass method of the associated class object. This is the famed Gafter's gadget.
- Using reflection to read the type parameters of the invoke method of the closure. In the current (2008-02-26) BGGA prototype, the invoke method is always the first method in the array returned by getMethods of the closure's class object, which simplifies the implementation.
- Using the getGenericInterfaces of the closure's class object. BGGA closures implement generic interfaces from package javax.lang.function, and the type parameters can be read out similarly as with Gafter's gadget.
@SuppressWarnings("unchecked")
|