#
Custom Annotations
This tutorial explains how to create and use custom annotations in Java.
Info
Java annotations are metadata (data about data) provided to the compiler and JVM. An annotation could be on classes, interfaces, variables, methods, or fields level. Annotations do not impact the execution of the code.
Let's create for the moment a custom annotation:
package com.example.demo;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
String projectStartDate() default "10-Jan-2020";
String programmerName();
}
Info
@Retention(RetentionPolicy.RUNTIME) will tell to the compiler to keep this annotation available during the runtime.
The annotation could be used on classes, interfaces, variables, methods, or fields level. I will use this annotation on a class level:
package com.example.demo;
@MyCustomAnnotation(programmerName="John")
public class Car {
String color;
public Car(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
And now let use it:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
System.out.println("---------------------------");
Car myCar1 = new Car("yellow");
MyCustomAnnotation myCustomAnnotation = myCar1.getClass().getAnnotation(MyCustomAnnotation.class);
System.out.println("field name: " + myCustomAnnotation.programmerName());
System.out.println("---------------------------");
}
}
Info
- As we can see the metadata included in annotation is available during the runtime. @Retention annotation can change this behaviour.
- By default, our custom annotation are not present in JavaDoc. To ensure that our custom annotations are shown in the documentation, we use @Documented.
- We can use @Target annotation to specify the level where this annotation could be used.
For example:
@Target(value= ElementType.METHOD)
. - @Inherited annotation could be used to let subclasses inherit that annotation.
- @Repeatable(MyCustomAnnotation.class) could be used if we want to use the custom annotation many times in the same place.