Why is Java's Class<T> generic?

JavaGenerics

Java Problem Overview


Why is Java's Class<T> generic?

Java Solutions


Solution 1 - Java

So that generic typed methods can be used -

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionripper234View Question on Stackoverflow
Solution 1 - JavaSteve B.View Answer on Stackoverflow
Solution 2 - JavaChris ArguinView Answer on Stackoverflow
Solution 3 - JavaBill the LizardView Answer on Stackoverflow
Solution 4 - JavaJérôme VerstryngeView Answer on Stackoverflow