Java annotation development

1. What is a comment

        Annontation is a new feature introduced in Java5, and the Chinese name is Annotation. It provides a secure annotation-like mechanism to associate any information or metadata with program elements (classes, methods, member variables, etc.). Add more intuitive and clear instructions to the program elements (classes, methods, member variables). These instructions have nothing to do with the business logic of the program and are used by the specified tool or framework. Annontation is like a modifier, applied to the declaration statements of packages, types, constructors, methods, member variables, parameters, and local variables.
        Java annotations are some meta-information attached to the code, which are used to analyze and use some tools during compilation and runtime, and play the function of explanation and configuration. Annotations will not and cannot affect the actual logic of the code, but only play a supporting role. Contained in the java.lang.annotation package.

Second, the classification of annotations

Annotation classification
As can be seen from the figure above: annotations are divided into three categories: mark annotations, standard meta annotations, and general annotations.
[Note]: Deprecated annotation, except for multiple strikethroughs, does not have any interception function.

3. Detailed explanation of standard meta annotations

        Standard meta-annotations are the annotations of custom annotations, which mainly contain 4, all of which are located in the java.lang.annotation package. We will use 4 standard meta-annotations when creating custom annotations. Their names and meanings are as follows:

  1. @Documented: Used to describe that other types of annotations should be used as public APIs for members of the annotated program, so they can be documented by tools such as javadoc. It is a mark annotation and has no members.

  2. @Inherited: Whether to allow subclasses to inherit this annotation

  3. @Retention: defines the life cycle of the annotation: some annotations only appear in the source code and are discarded by the compiler; while others are compiled in the class file; the annotations compiled in the class file may be used by the virtual machine Ignore, and others will be read when the class is loaded (please note that it does not affect the execution of the class, because the annotation and the class are separated in use). Use this meta-annotation to limit the "lifecycle" of custom annotations.
    The life cycle policy enumeration
    RetentionPolicy.RUNTIME annotation will exist in the class bytecode file and can be obtained through reflection at runtime.
    RetentionPolicy.CLASS default retention policy, discarded when the class is loaded. Useful in the processing of bytecode files. The annotation uses this method by default.
    RetentionPolicy.SOURCE is discarded during the compilation phase. These annotations no longer have any meaning after the completion of compilation, so they will not be written into bytecode. @Override, @SuppressWarnings are all such annotations.

  4. @Target: Explains the scope of the object modified by the annotation: annotations can be used for packages, types (classes, interfaces, enumerations, Annotation types), type members (methods, construction methods, member variables, enumeration values), method parameters And local variables (such as loop variables, catch parameters)
    modification range enumeration
    ElementType.CONSTRUCTOR acts on the constructor
    ElementType.FIELD acts on the domain/attribute
    ElementType.LOCAL_VARIABLE is used to describe the local variables
    ElementType.METHOD acts on the method
    ElementType.PACKAGE for description Package
    ElementType.PARAMETER is used to describe the parameter
    ElementType.TYPE is used to describe the class, interface (including annotation type) or enum declaration, the most commonly used
    ElementType.ANNOTATION_TYPE is another annotation

  5. @Repeatable: Repeatable naturally means repeatable. @Repeatable was only added in Java 1.8, so it is a new feature. What kind of annotation will be applied multiple times? Usually, the value of the annotation can be multiple at the same time. For example, a person is both a programmer and a product manager, and he is also a painter.

Four, custom annotations

1. Custom class annotation ClassAnnotation

package com.xsl;

import java.lang.annotation.*;

/**
 * @Description 自定义类注解
 * @Author xsl
 * @Date 2020/1/8 11:58
 **/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ClassAnnotation{
    
    
    String name() default "defaultService";
    String version() default "1.0.0.RELEASE";
}

2. Custom field annotation FieldAnnotation

package com.xsl;

import java.lang.annotation.*;

/**
 * @Description 自定义域注解
 * @Author xsl
 * @Date 2020/1/8 11:58
 **/
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldAnnotation {
    
    
    String name() default "defaultName";
    String value() default "defaultValue";
}

3. Custom method annotation enum MethodTypeEnum

package com.xsl;

/**
 * @Description 方法类型枚举
 * @Author xsl
 * @Date 2020/1/8 11:58
 **/

public enum MethodTypeEnum {
    
    
    TYPE1,TYPE2
}

4. Custom method annotation MethodAnnotation

package com.xsl;

import java.lang.annotation.*;

/**
 * @Description 自定义域注解
 * @Author xsl
 * @Date 2020/1/8 11:58
 **/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodAnnotation {
    
    
    String name() default "defaultName";
    MethodTypeEnum type() default MethodTypeEnum.TYPE1;
}

Five, test notes

1. Test annotation class

package com.xsl;

/**
 * @Description 注解测试类
 * @Author xsl
 * @Date 2020/1/8 11:58
 **/
@ClassAnnotation(name = "personBean",version = "1.2.0.RELEASE")
public class Person {
    
    
    @FieldAnnotation(name = "desc",value = "my personal annotation")
    private String desc;
    public String getDesc() {
    
    
        return desc;
    }
    public void setDesc(String desc) {
    
    
        this.desc = desc;
    }
    @MethodAnnotation(name="sayHello", type = MethodTypeEnum.TYPE2)
    public void sayHello() {
    
    
        System.out.println("Hello Annotation!");
    }
}

2. Testing

package com.xsl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Description 测试类
 * @Author xsl
 * @Date 2020/1/8 13:02
 **/
public class TestMyAnnotation {
    
    

    private static Person person = new Person();

    public static void main(String[] args) throws Exception {
    
    
        testClassAnnotation();
        System.out.println("-----------------------------------------");
        testFiledAnnotation();
        System.out.println("-----------------------------------------");
        testMethodAnnotation();

    }

    private static void testClassAnnotation(){
    
    
        Class<? extends Person> clazz = person.getClass();
        //因为注解是作用于类上面的,所以可以通过isAnnotationPresent来判断是否是一个具有指定注解的类
        if(clazz.isAnnotationPresent(ClassAnnotation.class)) {
    
    
            System.out.println("This is a class with annotation ClassAnnotation!");
            //通过getAnnotation可以获取注解对象
            ClassAnnotation annotation = clazz.getAnnotation(ClassAnnotation.class);
            if(null != annotation) {
    
    
                System.out.println("BeanName = " + annotation.name());
                System.out.println("BeanVersion = " + annotation.version());
            }else{
    
    
                System.out.println("the annotation that we get is null");
            }
        }else{
    
    
            System.out.println("This is not the class that with ClassAnnotation");
        }
    }


    private static void testFiledAnnotation() throws Exception {
    
    
        Class<?> clazz = person.getClass();
        //因为是注解到Field上的,所以首先要获取这个字段
        Field field = clazz.getDeclaredField("desc");
        //判断这个Field上是否有这个注解
        if(field.isAnnotationPresent(FieldAnnotation.class)) {
    
    
            System.out.println("===This is a field with annotation:FieldAnnotation!===");
            //如果有这个注解,则获取注解类
            FieldAnnotation annotation = field.getAnnotation(FieldAnnotation.class);
            if(null != annotation){
    
    
                System.out.println("before set the value is:" + person.getDesc());
                //通过反射给私有变量赋值
                field.setAccessible(true);
                field.set(person, annotation.value());
                System.out.println("after set the value is:" + person.getDesc());
            }else{
    
    
                System.out.println("the annotation that we get is null");
            }
        }else{
    
    
            System.out.println("This is not the class that with FieldAnnotation");
        }
    }

    private static void testMethodAnnotation() throws Exception {
    
    
        Class<?> clazz = person.getClass();
        //因为是注解到method上的,所以首先要获取这个方法
        Method method = clazz.getDeclaredMethod("sayHello");
        if(method.isAnnotationPresent(MethodAnnotation.class)) {
    
    
            System.out.println("===This is a method with a annotation:MethodAnnotation===");
            //通过getAnnotation可以获取注解对象
            MethodAnnotation annotation = method.getAnnotation(MethodAnnotation.class);
            if(null != annotation) {
    
    
                System.out.println("MethodName = " + annotation.name());
                System.out.println("MethodType = " + annotation.type());
            }else{
    
    
                System.out.println("the annotation that we get is null");
            }
        }else{
    
    
            System.out.println("This is not the class that with MethodAnnotation");
        }
    }
}

3. Perform screenshots

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44132240/article/details/103889951