Defining your own annotations

You can use the @interface annotation to create your own annotation definition.

Procedure

Use the @interface annotation to define your own annotation definition:
  • Annotation definitions resemble interface definitions
  • Annotation method declarations have neither parameters nor throws clauses, and return one of the following elements:
    • primitives
    • String
    • Class
    • enum
    • an array of the previously mentioned types
  • Methods can have default values
    public @interface CreatedBy{
         String name();
         String date();
         boolean contractor() default false;
    }          
    @CreatedBy(name = "Mary Smith",date="02/02/2008")
    public class MyClass{....}         

Results

Meta-annotations: Meta-annotations (annotations of annotations) provide additional information about how an annotation can be used:
  • @Target
    • Restricts the use of an annotation
    • Single argument must be from Enum ElementType
      • {TYPE, FIELD,METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE}
  • @Retention
    • Indicates where the annotation information is retained
    • Single argument must be from Enum RetentionPolicy
      • {SOURCE, CLASS, RUNTIME}
  • @Documented
    • Marker for annotations that are to be included in Javadoc
  • @Inherited
    • Marker for Type annotations that are to be inherited by subtypes
Other built-in annotations:
  • @Overrides
    • Applied to a method
    • Indicates that the compiler generates an error if the method does not actually override a superclass method.
  • @Deprecated
    • Applied to a method
    • Indicates that the compiler generates a warning when the method is used externally
  • @SuppressWarnings
    • Applies to a type or a method
    • Indicates that the compiler suppresses warnings for that element and all subelements
      @Deprecated
      public void oldMethod() {...}
      
      @SupressWarnings
      public void yesIknowIuseDeprecatedMethods() {...}
Icon that indicates the type of topic Task topic
Timestamp icon Last updated: July 17, 2017 21:58

File name: tdefiningannotations.html