Why is Java's Class<T>
generic?
4 Answers
So that generic typed methods can be used -
Class<Foo> klass = Foo.class;
Foo f = klass.newInstance();
Foo f = klass.cast(Object);

- 2,203
- 1
- 18
- 36

- 55,454
- 12
- 93
- 132
-
Warning to anyone believing this answer to be correct because it was accepted: This cannot be correct because the code does not compile. `klass` is uninitialized before it is used. – Dan Nissenbaum May 19 '11 at 05:28
-
5... (follow-up): Notice that code that does compile - namely, `Class
klass = Foo.class;` - begs the original question, because `Foo.class` seemingly provides the necessary information already. However, the ability to use generic typed methods is the correct answer; it's just not clear from the given example here. – Dan Nissenbaum May 19 '11 at 05:36
Here is a reasonably good summary of the advantages: http://download.oracle.com/javase/tutorial/extra/generics/literals.html

- 11,850
- 4
- 34
- 50
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

- 398,270
- 210
- 566
- 880
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.

- 57,710
- 92
- 283
- 453