注解实现原理

一、注解类型

  1. 源码注解。作用:对源码进行注释,编译成class文件后去除,通常是为了规范源码的格式。常见的有:Override,
  2. Class注解。作用:在ClassLoader加载时使用,jvm加载成功后,运行时将消失。
  3. 运行时注解。作用:在运行时使用,通常用于运行时生成指定对象,如Service,生成对象。Resource注入对象。

一、源码注解

目标:实现一个限定类字段命名格式的注解

1.1 实现步骤

参考博客
注解定义文件:

@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
public @interface NameCheck {
}

注解使用文件:

@NameCheck
public class NameCheckDemo {

}

注解解析文件:

@SupportedAnnotationTypes("NameCheck")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class NameCheckProcess extends AbstractProcessor {
    @SneakyThrows
    @Override
    public boolean process(Set annotations, RoundEnvironment roundEnv) {
        for (Element element : annotations) {
            ElementKind kind = element.getKind();
            switch (kind) {
                case CLASS:
                    return false;
                case ENUM:
                case INTERFACE:

                case METHOD:

                case FIELD:
                    return checkName(element);

                default:
                    this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "unknown element kind : " + kind);
                    return false;
            }
        }
        return true;
    }

    private boolean checkName(Element element) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "element:" + element);
        return element.getSimpleName().toString().startsWith("[a-z]");
    }
}

将Processer导入到编译时运行(这一步失败,没有正确导入,编译时没有触发检查)。

1.2 总结

前提:编译器支持插件注册,即可在编译器注册自己的插件进行编译,所有的插件都需要继承自AbstractProcessor类。
编译器的本质:格式检查和代码转换,检查代码格式的合法性并将java代码文件转换成class代码文件。

二、编译时注解

三、运行时注解

目标:实现一个运行时打印类名,方法名,内部字段名和函数参数名的注解。
定义运行时注解:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
public @interface NamePrint {
}

定义注解测试类:

public class NameCheckDemo {

    @NamePrint
    private int checkDemo;
}

@NamePrint
public class NamePrintDemo {
    @NamePrint
    public void testPublicMethod () {

    }

    @NamePrint
    private void testPrivateMethod() {

    }

    @NamePrint
    private String testPrivateField;

    @NamePrint
    public String testPublicField;

    @NamePrint
    public void testParam(@NamePrint String param1, int param2) {

    }
}

定义运行时注解处理测试函数:

class NamePrintDemoTest {
    @Test
    public void testRuntime() {
        Reflections reflections = new Reflections("com.brave.springtest.annotation"); // 从指定包获取Reflections
        Set> classesList = reflections.getTypesAnnotatedWith(NamePrint.class);
        classesList.forEach(classes -> {
            if (classes.getAnnotation(NamePrint.class) != null) {
                System.out.println("Class : " + classes.getSimpleName());
            }

            Arrays.stream(classes.getMethods()).forEach(method -> {
                String methodName = classes.getSimpleName() + "." + method.getName();
                if (method.getAnnotation(NamePrint.class) != null) {
                    System.out.println("Method : " + methodName);
                }

                Arrays.stream(method.getParameters()).forEach(parameter -> {
                    if (parameter.getAnnotation(NamePrint.class) != null) {
                        System.out.println("Parameter : " + methodName + "." + parameter.getName());
                    }
                });
            });

            Arrays.stream(classes.getDeclaredFields()).forEach(field -> {
                if (field.getAnnotation(NamePrint.class) != null) {
                    System.out.println("Field : " + classes.getSimpleName() + "." + field.getName());
                }
            });
        });

        // 从指定包获取扫描所有类上面的字段的注解
        new Reflections("com.brave.springtest.annotation", new FieldAnnotationsScanner()).getFieldsAnnotatedWith(NamePrint.class).forEach(field -> {
            if (field.getAnnotation(NamePrint.class) != null) {
                System.out.println("Field : " + field.getName());
            }
        });
    }

}

输出如下:

// 按类从上往下扫描的
Method : NamePrintDemo.testPublicMethod
Method : NamePrintDemo.testParam
Parameter : NamePrintDemo.testParam.param1
Field : NamePrintDemo.testPrivateField
Field : NamePrintDemo.testPublicField

// 下方扫描内部字段上的注解
Field : testPublicField
Field : testPrivateField
Field : checkDemo

总结:

  1. 运行时注解的前提是反射,即通过反射可以获得包中任何一个符号(包括类,字段,方法,参数)等的定义。
  2. Reflections提供了基于字段或者方法的扫描接口,可以不需要从类开始往下递归扫描。
  3. 运行时注解通常用来生成变量,如Service注解生成类对应的变量,Resource注解将生成的变量注入其中。

你可能感兴趣的:(注解实现原理)