What are annotations in Java?

An annotation adds information (metadata) to classes, methods and fields. It does not change the code by itself. The compiler or a framework reads it. Well known ones: @Override, @Deprecated, @FunctionalInterface, @SuppressWarnings. Frameworks like Spring use many.

You can make your own, and read it with reflection:

import java.lang.annotation.*;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Run {
    String value() default "no name";
}

public class Main {
    @Run("first")
    public void alpha() { System.out.println("alpha called"); }

    public void beta() { }

    @Run
    public void gamma() { System.out.println("gamma called"); }

    public static void main(String[] args) throws Exception {
        Main obj = new Main();
        for (String name : new String[]{"alpha", "beta", "gamma"}) {
            Method m = Main.class.getMethod(name);
            Run run = m.getAnnotation(Run.class);
            if (run != null) {
                System.out.println("Running " + run.value());
                m.invoke(obj);
            } else {
                System.out.println(name + " has no @Run");
            }
        }
    }
}
Output

Running first
alpha called
beta has no @Run
Running no name
gamma called


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.