How to pass variables into Java annotations?

In Java, annotations can pass values to variables using the following methods:

  1. Create an annotation, declare a member variable, and provide a default value for it.
public @interface MyAnnotation {
    String value() default "";
}
  1. Pass the value of the variable where it is used in the annotation.
@MyAnnotation(value = "Hello World")
public class MyClass {
    // ...
}
  1. In the places where annotations are used, you can retrieve the values of the annotations through reflection.
public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        MyAnnotation annotation = obj.getClass().getAnnotation(MyAnnotation.class);
        String value = annotation.value();
        System.out.println(value); // 输出: Hello World
    }
}

In the above code, we defined an annotation called MyAnnotation and applied it to the MyClass class, passing a string “Hello World” as the annotation value. Then, in the Main class, we used reflection to retrieve the MyAnnotation annotation on the MyClass class and obtained the annotation’s value. Finally, we printed the retrieved value.

bannerAds