Search code examples
javagenericsjava-5

How is the compile time check of the type of annotations changed in Java 5?


I am looking at the changes introduced in Java 5 , the following piece of documentation looks unclear to me .

<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.

I would still have been able to make the compiler check that the parameter represented a subclass of Annotation by using Annotation as the parameter type . What am I missing here, how is the compile time check changed with the introduction of generics?

I agree that I will not need to cast the result now though.


Solution

  • "...represented a subclass..." does not mean instance of a subclass. In that case you could use Annotation as a parameter type. It instead means an instance of Class that corresponds to a subclass of Annotation.

    Without generics:

    Annotation getAnnotation(Class annotationType);
    

    You could pass any Class to the method. For instance:

    SomeType.class.getAnnotation(Object.class);
    

    While Object is not actually a subtype of Annotation.

    But with generics, you have a type bound, and the Class itself has a generic parameter that is the type it encodes.

    With generics, passing Object.class, which has the type of Class<Object>, would throw a compiler error, since T would be Object, and Object does not conform to the bound: <T extends Annotation>.