Tuesday, July 22, 2008

Why Class<T> is parameterized?

Generics are not an easy concept in the Java language, escpecially when you are dealing with some sofisticated wildcards, but still you can grasp this concept in quite a short time. There's even a more difficult task - understand why the developers of the language choose some implementation over another, or introduced parameters in some classes.
Let's take the Class class. It is not a container, so it is not evident from the first sight, why do we have a parameter here. You start getting "Class is a raw type. References to generic type Class should be parameterized." warnings everywhere, and replacing those Class variable with Class<?> looks no good. So - why did they do it?
The best answer to such questyions is to look at the source code, and find references to the parameter. Almost instantly you'll see, that the newInstance() method returns now T, which gives us a very powerful premise to create object factories with strong typing. Like this:

public static <T> Collection select(Class<T> c, int times) {
Collection<T> result = new ArrayList<T>();
for (int i=0; i<times; i++) {
T item = c.newInstance();
result.add(item);
}
return result;
}

This example is oversimplified, but you should already see, what a gift we've got here!