Creating and Using Custom Annotations
suggest changeA custom annotation needs two decisions:
- Target: where it can be applied, such as a field, a method, or a type.
- Retention: how long it is kept.
The JDK provides meta-annotations for those decisions. The ones used most often are:
@Target
@Retention
Creating Custom Annotation
@Retention(RetentionPolicy.SOURCE) // will not be available in compiled class
@Target(ElementType.METHOD) // can be applied to methods only
@interface CustomAnnotation{
int value();
}
Using Custom Annotation
class Foo {
@CustomAnnotation(value = 1) // will be used by an annotation processor
public void foo() {}
}
The value inside @CustomAnnotation is read by an annotation processor, which may generate code at compile time.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents