Pure Danger Tech


Interesting tidbit on generics and Class

20 Oct 2006

I’m using JDK 5 stuff in earnest for the first time and ran across an interesting little thing (to me at least) while implementing a ClassLoader. I noticed that the method ClassLoader.loadClass(String name) returns a Class<?>. It wasn’t intuitively obvious to me what this was.

On second glance, the <?> is just a type annotation representing any possible type. But then it seemed odd to me that Class was parameterized. So, I cracked open the source for Class and looked through it. Class is parameterized based on the type of the instances it can create via newInstance(). So, Class serves the abstract role of a factory and is parameterized by the type of the objects returned by the factory. Pretty cool. Seems like this might be a more generizable pattern for abstract factory-like classes (ones not bound to producing a specific concrete class).