The Retention Policy of Annotation specifies its durability.
Some Annotation are available only in source code,
some in Class byte code format and others available at Runtime.
We can specify the Retention Policy with @Retention annotation.
The possible Retention Policies are listed below,
RetentionPolicy.SOURCE
Available in source code only.
RetentionPolicy.CLASS
Available in source code and class byte code.
RetentionPolicy.RUNTIME
Available in source code, class byte code and at Runtime.
Two Annotations with Retention Policy RUNTIME are shown below,
public void setFieldOne(int fieldOne) { this.fieldOne = fieldOne;
}
public String getFieldTwo() { return fieldTwo;
}
public void setFieldTwo(String fieldTwo) { this.fieldTwo = fieldTwo;
}
}
Only the Annotations with Retention Policy RUNTIME are accessible using Reflection API.
The following example shows how to access Annotations at runtime.