Java - Annotation Types Restrictions

Introduction

An annotation type has some restrictions.

An annotation type cannot inherit from another annotation type.

Every annotation type implicitly inherits the java.lang.annotation.Annotation interface, which is declared as follows:

  
package java.lang.annotation; 
  
public interface Annotation { 
        boolean equals(Object obj); 
        int hashCode(); 
        String toString(); 
        Class<? extends Annotation> annotationType(); 
} 

All of the four methods declared in the Annotation interface are available in all annotation types.

Method declarations in an annotation type cannot have any parameters and cannot have a throws clause.

The return type of a method declared in an annotation type must be one of the following types:

Any primitive type: byte, short, int, long, float, double, boolean, and char

  • java.lang.String
  • java.lang.Class
  • An enum type
  • An annotation type
  • An array of any of the above mentioned type

You can use a generic return type to return a user-defined class type.

class Test{}
@interface My { 
        Class element1(); // Any Class type 
        Class<Test> element2(); // Only Test class type 
        Class<? extends Test> element3(); // Test or its subclass type 
}  

An annotation type cannot override a method in the Object class or the Annotation interface.

An annotation type cannot be generic.