Why is Java's Class<T> generic?

So that generic typed methods can be used -

Class<Foo> klass = Foo.class;
Foo f = klass.newInstance();
Foo f = klass.cast(Object);

Here is a reasonably good summary of the advantages: http://download.oracle.com/javase/tutorial/extra/generics/literals.html


There's a short mention of this in the Generics section of the 1.5 version of the language guide:

More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information. This enables a style of static factories exemplified by the getAnnotation method in the new AnnotatedElement interface:

<T extends Annotation> T getAnnotation(Class<T> annotationType); 

This is a generic method. It infers the value of its type parameter T from its argument, and returns an appropriate instance of T, as illustrated by the following snippet:

Author a = Othello.class.getAnnotation(Author.class);

Prior to generics, you would have had to cast the result to Author. Also you would have had no way to make the compiler check that the actual parameter represented a subclass of Annotation


The real reason is given by Neil Gafter:

When we added generics to Java in JDK5, I changed the class java.lang.Class to become a generic type. For example, the type of String.class is now Class < String > . Gilad Bracha coined the term type tokens for this. My intent was to enable a particular style of API, which Joshua Bloch calls the THC, or Typesafe Heterogenous Container pattern.