# Custom Annotations

In 
Published 2024-01-06

This tutorial explains how to create and use custom annotations in Java.

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();
}

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("---------------------------");
	}
}