Defining and using annotations

You can use the @Interface annotation to define your own annotation definition.

Defining your own annotations

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
    • array of the above types
  • Methods may 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{....}         
Meta-annotations: Meta-annotations (annotations of annotations) provide additional information on how an annotation should 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 will be retained
    • Single argument must be from Enum RetentionPolicy
      • {SOURCE, CLASS, RUNTIME}
  • @Documented
    • Marker for annotations that should 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 should generate an error if the method does not actually override a superclass method.
  • @Deprecated
    • Applied to a method
    • Indicates that the compiler should generate a warning when the method is used externally
  • @SuppressWarnings
    • Applies to a type or a method
    • Indicates that the compiler should supress warnings for that element and all subelements
      @Deprecated
      public void oldMethod() {...}
      
      @ SupressWarnings
      public void yesIknowIuseDeprecatedMethods() {...}