java—Annotation

Annotation is a mechanism for providing metadata description, which can add metadata information to program elements such as classes, fields, methods, and parameters. Annotation can be processed at compile time, and their information can also be obtained through the Java reflection mechanism at runtime.

The following is an example of using Annotation in Java SE:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    
    
    String name();
    int age() default 20;
    String[] hobbies();
}

In this example, MyAnnotation is an annotation, which is defined as @Retention(RetentionPolicy.RUNTIME) and @Target(ElementType.METHOD), indicating that it still exists at runtime and acts on the method. The annotation contains three elements, namely name, age and hobbies, among which the age element has a default value of 20.

Here's an example of how to use MyAnnotation on a method:

public class MyClass {
    
    
    @MyAnnotation(name = "John Smith", hobbies = {
    
    "reading", "writing"})
    public void myMethod() {
    
    
        // 方法体
    }
}

In this example, we added MyAnnotation to the myMethod method, and added the values ​​of the name and hobbies elements to it. According to the definition above, the age element uses a default value of 20.

We can use the reflection mechanism to get the element value in the MyAnnotation annotation, for example:

public class AnnotationDemo {
    
    
    public static void main(String[] args) throws Exception {
    
    
        MyClass obj = new MyClass();
        Method method = obj.getClass().getMethod("myMethod");
        MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
        System.out.println("name: " + annotation.name());
        System.out.println("age: " + annotation.age());
        System.out.println("hobbies: ");
        for (String hobby : annotation.hobbies()) {
    
    
            System.out.println(hobby);
        }
    }
}

This example obtains the MyAnnotation annotation on the myMethod method through the reflection mechanism, and outputs all element values.

Running the above code will result in the following output:

name: John Smith
age: 20
hobbies: 
reading
writing

Guess you like

Origin blog.csdn.net/l_010/article/details/131234553