Skip to content

Latest commit

 

History

History
65 lines (50 loc) · 2.44 KB

01. Annotations.md

File metadata and controls

65 lines (50 loc) · 2.44 KB

Annotations

  • feature that enables you to embed supplemental information into a source file.
  • A.K.A metadata, designed mostly for use by development and deployment tools.
  • it is created through a mechanism based on the interface.
@interface MyAnnotation{
    String str();
    int value();
}
  • the @ preceding the keyword interface tells the compiler an annotation type is being declared.
  • Annotation consists solely of method declarations. but you will not be providing with the method bodies.
  • methods declared inside annotations cannot have parameters.
  • java implements the methods. Moreover, the methods act like fields.
  • it cannot include an extends clause. however, all annotation types automatically extends the Annotation interface.
@MyAnno(str="hello",value=44)
public static void method(){}
  • The string "hello" is assigned to the str member of MyAnno.
  • when an annotation member is given a value, only its name is used. hence, annotation members look like fields here.

Annotation Retention Policy

  • A retention policy determines at what point an annotation is discarded.
  • java defines three such policy which are encapsulated within the java.lang.annotation.RetentionPolicy enumeration.
  • They are : SOURCE , CLASS(default), RUNTIME
  • SOURCE : An annotation with this retention policy is retained only in the source fie and is discarded during compilation.
  • CLASS : An annotation with this retention policy is stored in the .class file during compilation. however it is not available through JVM during runtime.
  • RUNTIME : An annotation with this retention policy is stored in the .class file during compilation and is available through JVM during runtime.
  • Runtime offers the greatest annotation persistence.
  • An annotation on a local variable declaration is not retained in the .class file.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    String str();
    int value();
}

Restrictions

  • annotation cannot inherit another annotation.
  • methods declared cannot have any parameters.
  • methods cannot specify a throws clause.
  • methods must return one of the following:
    • A primitive type: int, double, etc
    • An object of type String or Class
    • An object of an enum type
    • An object of another annotation type
    • An array of a legal type.
  • annotations cannot be generic.