Java Annotations

Sayeed Far Ooqui
1 min readNov 10, 2021

java Annotations

Annotations are only metadata and do not contain any business logic.Annotations only provide information about the attribute (class/method/package/field) on which it is defined.

@Retention – Defines how long the annotation should be kept.

RetentionPolicy.SOURCEDiscard during the compile. These annotations don’t make any sense after the compile has completed, so they aren’t written to the bytecode. Examples: @Override, @SuppressWarnings

RetentionPolicy.CLASSAnnotations are to be recorded in the class file by the compiler. but not loaded by the at run time.Discard during class load. Useful when doing bytecode-level post-processing. Somewhat surprisingly, this is the default.

RetentionPolicy.RUNTIMEDo not discard. The annotation should be available for reflection at runtime. This is what we generally use for our custom annotations.example @Component

@Target –Where annotation can be placed. If you don’t specify this, annotation can be placed anywhere.example method, value.

@Inherited – Controls whether the annotation should affect the subclass.

All attributes of annotations are defined as methods, and default values can also be provided.

If we have only one attribute inside an annotation, it should be named “value” and can be used without attribute name while using it.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo {
public enum Priority {LOW, MEDIUM, HIGH}
public enum Status {STARTED, NOT_STARTED}
String author() default “Yash”;
Priority priority() default Priority.LOW;
Status status() default Status.NOT_STARTED;
}

nb: @override annotation has already defined in build in java. in order to create similar annotaion for overloading method we could create an anotaion and write another class for the annotation to specify the function which tha annotation has to be done.

--

--