Java 注解Annotation初探

Springauto源代码都包含了很多自定义的注解,想着想要深入学习,还是得先了解下注解(Annotation)

注解定义

注解是在JDK1.5 开始引入的新特征。
对于Java 开发者来说,或多或少都会接触到@Override,@param等注解,这些注解的功能都很熟悉。注解就好像一个标签一样,标明了这个类,方法,成员变量等应该具有的行为或作用。

注解原理

说到底,注解就好像一个JavaBean,举例来说:

@JSONField(name="test",unwarpped=true)

相当于定义一个JSONField对象,这个对象的name属性为test,unwarpped属性为true.然后通过在定义注解@Retention属性说明在什么时候解析这个JavaBean,并通过实现接口,让编译器指定的时候执行一系列操作,比如依赖检查,文档生成等。

注解实战

首先我们需要明白一些关于注解的知识:

java.lang.annotation提供了四种元注解,专门注解其他的注解(在自定义注解的时候,需要使用到元注解):

  • @Retention: 定义该注解的生命周期
    • RetentionPolicy.SOURCE: 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@Override, @SuppressWarnings都属于这类注解。
    • RetentionPolicy.CLASS : 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式
    • RetentionPolicy.RUNTIME : 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。
  • @Target: 表示该注解用于什么地方。默认值为任何元素,表示该注解用于什么地方。可用的ElementType参数包括
    • ElementType.CONSTRUCTOR:用于描述构造器
    • ElementType.FIELD:成员变量、对象、属性(包括enum实例)
    • ElementType.LOCAL_VARIABLE:用于描述局部变量
    • ElementType.METHOD:用于描述方法
    • ElementType.PACKAGE:用于描述包
    • ElementType.PARAMETER:用于描述参数
    • ElementType.TYPE:用于描述类、接口(包括注解类型) 或enum声明
  • @Documented: 一个简单的Annotations标记注解,表示是否将注解信息添加在java文档中。

  • @Inherited: 定义该注释和子类的关系
    @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

实战:

如何自定义注解,网上基本都有,不过都是一些简单的运行时注解,感觉就像定义了一个JavaBean,这里我们定义一个编译时注解。

首先定义一个注解类型:

package com.dengchengchao.annotationtest;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author dengchengchao
 * @date 18-7-26 下午5:44
 */
//定义注解生效时间段
@Retention(RetentionPolicy.CLASS)
//注解作用范围
@Target(ElementType.METHOD)
public @interface Annotation {
    int layoutId() default 0;
    int viewType() default 0;
    String viewHolder();
}

然后定义一个处理此注解类型的注解处理器:

package com.dengchengchao.annotationtest;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import java.util.HashSet;
import java.util.Set;

/**
 * @author dengchengchao
 * @date 18-7-26 下午5:42
 */
//指定支持的注解
@SupportedAnnotationTypes("com.dengchengchao.annotationtest.Annotation")
//定义最低支持的jdk版本
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class AnnotationProcessor extends AbstractProcessor {


    public AnnotationProcessor() {
      super();
    }

    //将需要支持的注解保存在Set中,用于注册此注解
    private Set<String> supportedAnnotationTypes = new HashSet<String>();

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        //获取标记注解的类名
        supportedAnnotationTypes.add(Annotation.class
                .getCanonicalName());
    }

    /**
     * 主要方法,此方法会根据注解定义的@Retention在指定的时间段执行
     *
     *
     * @param annotations 所有支持的注解类型
     * @param roundEnv 注解所在位置的周围环境信息,执行注解的时候主要从这个参数获取信息
     * @return 此处理器是否声明了这些注释类型,如果返回true,则表示后续处理器不必再处理此注解,返回false表示后面的处理器应该继续处理他们
     */
    @Override
    public boolean process(Set<? extends TypeElement> annotations,
                           RoundEnvironment roundEnv) {
        Messager messager = processingEnv.getMessager();
        for (TypeElement typeElement : annotations) {
            for (Element element : roundEnv
                    .getElementsAnnotatedWith(typeElement)) {
                String info = "name = " + element.toString();
                messager.printMessage(Diagnostic.Kind.NOTE, info);
                //获取Annotation
                Annotation annotation = element
                        .getAnnotation(Annotation.class);

                if (annotation != null) {
                    int layoutId = annotation.layoutId();
                    int viewType = annotation.viewType();
                    String viewHolder = annotation.viewHolder();
                    messager.printMessage(Diagnostic.Kind.NOTE, "layoutId = " + layoutId
                            + ",viewType = " + viewType + ",viewHolder = "
                            + viewHolder);
                }

            }
        }
        return false;
    }


    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        return supportedAnnotationTypes;
    }
}

由于是编译时类型,我们必须告知编译器在编译的时候调用此注解处理器:

在项目工程的resources/META-INF/services目录下新建javax.annotation.processing.Processor文件,在文件中写明需要注册的注解处理器类(如果有多个处理器,则每个处理器占一行)

com.dengchengchao.annotationtest.AnnotationProcessor

项目到这里就已经完成,可以使用工具打包为jar包,不过这里大多数都是Maven项目工程.贴出POM


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dengchengchao.MyAutoValue</groupId>
    <artifactId>MyAutoValue</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <!--JDK配置-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <mybatis-spring-boot>1.2.0</mybatis-spring-boot>
        <java.version>1.6</java.version>
    </properties>


    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>{java.version}</source>
                    <target>{java.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                    <compilerArgument>-proc:none</compilerArgument>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

注意到后面必须添加编译选项 -proc:none

到此为止,编译形注解完成
新建一个类,添加一个方法:

 package com.dengchengchao.annotationtest;

/**
 * @author dengchengchao
 * @date 18-7-26 下午6:01
 */
public class Main {

    @Annotation(layoutId = 100,viewType = 1,viewHolder = "com.dengchengchao.test")
    public void fun(){

    }


}

编译此java文件:

javac -cp  MyAutoValue-1.0-SNAPSHOT.jar Main.java 

输出结果如下:

Note: name = fun()
Note: layoutId = 100,viewType = 1,viewHolder = com.dengchengchao.test

参考文章:
深入Dagger:自定义AutoValue

Java自定义AnnotationProcessor处理自己的Annotation

注解Annotation实现原理与自定义注解例子