Pure Danger Tech


Solving a generics problem with Gafter’s Gadget

25 Jan 2007

I mentioned in my prior post on generics that I had encountered some circumstances recently in framework design where I couldn’t find a solution to my generics dilemma, but I couldn’t remember the details. Well, I just read Neal Gafter’s post on Super Type Tokens and it jogged my memory, as this was exactly the problem I ran into – needing something like this: List<String>.class which just isn’t possible. Apparently it’s not an uncommon thing as Ted Neward, Eric Burke, Bob Lee, and surely others have all run into it.

I guess the proposed solution is in Neal Gafter’s blog and is Super Type Tokens, which can be implemented now as a class. Specifically, an abstract generic class (called TypeReference in his blog, and referred to as “Gafter’s Gadget”). At usage time, you subclass into an anonymous type (at that point providing the generic type). You can then reflectively discover the specified generic type from the TypeReference instance. Even better would be to include it in the JDK itself as a utility, as Neal suggests.

Actually, now that I think about it, this even harkens back to my very first post about generics as I discovered that Class was now typed by the type of object it could construct and I posited that this could be a general factory pattern. I later discovered that this is actually mentioned in the generics documentation. Bob Lee’s version (in Neal Gafter’s blog) is basically an extension of that muddled insight into the land of generics, providing for a generic factory as well.