52

Why is Java's Class<T> generic?

sth
  • 222,467
  • 53
  • 283
  • 367
ripper234
  • 222,824
  • 274
  • 634
  • 905

4 Answers4

34

So that generic typed methods can be used -

Class<Foo> klass = Foo.class;
Foo f = klass.newInstance();
Foo f = klass.cast(Object);
Caesar Ralf
  • 2,203
  • 1
  • 18
  • 36
Steve B.
  • 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
15

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

Chris Arguin
  • 11,850
  • 4
  • 34
  • 50
14

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

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
8

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.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453