java annotations are easy to use

Posted by gotit on Mon, 20 Jul 2020 16:23:01 +0200

java annotations are easy to use

Annotations have been used throughout the development process, and today I finally want to look at the implementation of annotations.Drive directly

// Custom Notes
// Annotation has been implemented here
// Note that comments are only valid in the form of reflection calls
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD,ElementType.FIELD})
public @interface InterfaceTest {
    String value();
}

Our custom annotations are developed with jdk annotations
The @Retention comment is used to tell the compiler how to work
- @Retention (value =RetentionPolicy.RUNTIME) The compiler will record the comment in the class file, and the VM will retain the comment at run time, so it can be read reflectively.
Comments to be discarded by the SOURCE compiler.
The CLASS compiler records comments in the class file, but the VM does not need to keep comments at runtime.This is the default behavior.
RUNTIME for general development

@Target mainly tells you where this annotation works and you can use multiple

@Target (value =ElementType.METHOD) Function in method
FIELD field declaration (including enumeration constants) properties
TYPE class, interface (including comment type), or enumeration declaration
ANNOTATION_TYPE Annotation Type Declaration
CONSTRUCTOR construction method declaration

public class TestInterfaceTest {

    @InterfaceTest(value = "Ha ha ha")
    public static String name;

    public static void main(String[] args) throws Exception {
        Class<TestInterfaceTest> aClass = TestInterfaceTest.class;
        Object obj = aClass.newInstance();
        Method method = aClass.getMethod("test", new Class[]{int.class});
        // Is annotation used
        boolean annotationPresent = method.isAnnotationPresent(InterfaceTest.class);

        if (annotationPresent) {
            // Get this comment
            InterfaceTest annotation = method.getAnnotation(InterfaceTest.class);
            // Get the value on the comment
            String value = annotation.value();
            Object invoke = method.invoke(obj, 1);
            System.out.println(value + invoke);
        }
        Field name = aClass.getField("name");
        boolean is = name.isAnnotationPresent(InterfaceTest.class);
        if (is) {
            InterfaceTest annotation = name.getAnnotation(InterfaceTest .class);
            String value = annotation.value();
            name.set(obj,value);
        }

        System.out.println(InterfaceTest.name);
    }

    @InterfaceTest(value = "Annotated Value")
    public int test(int s) {
        System.out.println("===============");
        return s;
    }
}

Topics: Java JDK