Annotations in Java

@Override
public void run() {
System.out.println("running..");
}
@Author(
name = "John Doe",
date = "09/14/2021"
)
public class HelloWorld {
}
  1. Built-in annotations in Java.
  2. Creating own custom annotations.

Built-in annotations in Java

// example
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface FileWriter {
String filePath();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {
String name();
}
@Target(ElementType.ANNOTATION_TYPE) - to use in other annotations
@Target(ElementType.CONSTRUCTOR) - to use in contructor declaration
@Target(ElementType.FIELD) - to use in field declarions
@Target(ElementType.LOCAL_VARIABLE) - local variable declarations
@Target(ElementType.METHOD) - to use in method declarions
@Target(ElementType.MODULE) - to use in modules
@Target(ElementType.PACKAGE) - to use in package declaraions
@Target(ElementType.PARAMETER) - to use in parameters
@Target(ElementType.TYPE) - to use in class, interface (including annotation type), or enum declaration
@Target(ElementType.TYPE_PARAMETER) - type prameter declaraion
@Target(ElementType.TYPE_USE) - Use of a type
  1. CLASS — Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
  2. RUNTIME — Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively. In this mode, it can be used by reflection.
  3. SOURCE — Annotations are to be discarded by the compiler.
import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface RestClient {
String url();
RequestMethod requestMethod();
String contentType();
}

Creating own custom annotations

Summary

  1. https://www.geeksforgeeks.org/annotations-in-java/
  2. https://docs.oracle.com/javase/tutorial/java/annotations/basics.html

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store