android 注解的使用

作者: 许方镇 | 来源:发表于2017-02-07 14:41 被阅读1122次

    前言

    对注解,一开始是在学习java的时候接触到的,就是在《Thinking in Java》里草草看过。后来开发android,自己接了项目时,把xUtils3里的注解模块抠出来使用了,再到后来毕业了来了大公司,同事们都说不要使用注解,用反射影响性能,于是,注解就从入门到放弃了。后来发现注解也可以在编译时生成代码,并不会怎么影响性能,于是准备写点来复习下注解

    基础概况

    注解是Java SE5中的重要特性,也被称为元数据。为我们在代码中添加信息提供一种形式化的方式,使我们可以在稍后某个时刻非常方便地使用这些数据。主要作用:

    1. 可以由编译器来测试和验证格式
    2. 存储有关程序的额外信息
    3. 可以用来生成描述符文件或新的类定义
    4. 减少编写样板代码的负担

    分类

    • 根据注解中成员个数(0个,1个,多个)把注解分为:标记注解,单值注解,完整注解
    • 也可以根据把注解的来源分为jdk自带的,元注解,和我们自己定义的注解
    1. Java SE5中自带了三种标准注解

    @Override 表示当前的方法定义将覆盖超类中的方法
    @Deprecated 表示废弃的意思,使用了该注解的方法或者对象,则会有提示。
    @SuppressWarnings 关闭不当的编译器警告信息
    java 8新特性:加入了 @Repeatable注解,允许多次使用同一个注解

    @Repeatable(Authorities.class)
    public @interface Num{
         int value();
    }
    
    public class Opera{
        @Num(value = 1)
        @Num(value = 2)
        public void add(){ }
    }
    
    2. Java SE5中还有四个元注解,元注解专职负责注解其他注解。在 java.lang.annotation下
    元注解 作用
    @Target 表示该注解可以用于什么地方,可能在ElementType参数包括
    **CONSTRUCTOR: 用于描述构造器
    FIELD: 用于描述域
    LOCAL_VARIABLE: 用于描述局部变量
    METHOD: 用于描述方法
    PACKAGE: 用于描述包
    PARAMETER: 用于描述参数
    TYPE: **用于描述类、接口(包括注解类型) 或enum声明
    @Retention 表示需要在什么级别保存该注解信息。可选的RetentionPolicy参数包括:
    **SOURCE: 注解将被编译器丢弃
    CLASS: 注解在class文件中可用,但会被VM丢弃。
    RUNTIME: **VM将在运行期也保留注解,因此可以通过反射机制读取注解的信息
    @Document 将此注解包含在javadoc中
    @Inhrited 允许子类继承父类中的注解

    java 8新特性:java 8之前注解只能是在声明的地方所使用,比如类,方法,属性;java 8里面,注解可以应用在任何地方,比如方法参数前面等。

    3.自定义注解

    先写几个简单的注解:

    1. 没有元素的标记注解
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Test {}
    
    1. 单值注解
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Num {
        int value();
    }
    
    1. 完整注解
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Event {
        int[] value();
        int[] parentId() default 0;
        Class<?> type() default View.OnClickListener.class;
        String setter() default "";
        String method() default "";
    }
    
    自定义注解格式:

    public @interface 注解名{注解体}。注解体中注解元素可以被public修饰,也可以什么也不写,元素类型可以是:

    • 所有基本数据类型(int,float,boolean等)
    1. String类型
    2. Class类型
    3. enum类型
    4. Annotation类型(说明注解可以嵌套)
    5. 以上所有类型的数组
    默认值的限定:

    编译器对默认值过分的挑剔,要么有确定的默认值,要么在使用的时候提供元素的值。
    基本类型的元素都有默认值,不用写default也可以,但是想String这类就必须要写,而且不能写null,因此在某些需要分清是null还是空字符串的地方要注意。

    4. 注解的使用
    @Event(value = R.id.btn_test1, type = View.OnClickListener.class)
    private void onTestClick(View view) {
        ……
    }
    

    注解元素使用时变现为键值对的形式,如上的value=R.id.btn_test1,没有赋值的就用默认的值了。
    当然为了简便,也可以直接写上值,特别是单值注解

    @Num (2)
    class Goods {
    ……
    }
    
    5. 注解处理器类库的使用

    如果没有用来读取注解的工具,那注解也不会比注释更有用。使用注解的过程中很重要的一个部分就是创建与使用注解处理器。Java SE5扩展了反射机制的API,在java.lang.reflect 包下新增了AnnotatedElement接口,该接口代表程序中可以接受注解的程序元素,以下是源码,不要看到接口里的方法有具体实现感到惊讶(Java 8允许我们给接口添加一个非抽象的方法实现,只需要使用 default关键字即可,这个特征又叫做扩展方法),原来的注释太长我去掉了,写上简单的汉字注释,java 8比起之前新增了两个方法。

    public interface AnnotatedElement {
    
        //该元素是否被注解标记了
        default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
            return getAnnotation(annotationClass) != null;
        }
    
        //获取该元素指定注解类型的值
        <T extends Annotation> T getAnnotation(Class<T> annotationClass);
    
        //获取该元素所有的注解
        Annotation[] getAnnotations();
    
        //1.8新增,返回重复注解(@Repeatable)的类型
        default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
    
            T[] result = getDeclaredAnnotationsByType(annotationClass);
    
            if (result.length == 0 && // Neither directly nor indirectly present
                    this instanceof Class && // the element is a class
                    AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
                Class<?> superClass = ((Class<?>) this).getSuperclass();
                if (superClass != null) {
                    // Determine if the annotation is associated with the
                    // superclass
                    result = superClass.getAnnotationsByType(annotationClass);
                }
            }
    
            return result;
        }
    
        //返回直接存在于此元素上的所有注释,不考虑继承下来的
        default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
            Objects.requireNonNull(annotationClass);
            // Loop over all directly-present annotations looking for a matching one
            for (Annotation annotation : getDeclaredAnnotations()) {
                if (annotationClass.equals(annotation.annotationType())) {
                    // More robust to do a dynamic cast at runtime instead
                    // of compile-time only.
                    return annotationClass.cast(annotation);
                }
            }
            return null;
        }
    
        //1.8新增,返回直接或者间接标记在该元素的注解类型,不考虑继承。
        default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
            Objects.requireNonNull(annotationClass);
            return AnnotationSupport.
                    getDirectlyAndIndirectlyPresent(Arrays.stream(getDeclaredAnnotations()).
                            collect(Collectors.toMap(Annotation::annotationType, Function.identity(),
                                    ((first, second) -> first), LinkedHashMap::new)), annotationClass);
        }
    
        Annotation[] getDeclaredAnnotations();
    }
    

    该接口主要有如下几个实现类:

    • Class:类定义
    • Constructor:构造器定义
    • Field:累的成员变量定义
    • Method:类的方法定义
    • Package:类的包定义

    通过反射获取成员名再获取注解值得一般写法,同样的可以通过反射获取方法等

    Field fields[] = clazz.getDeclaredFields();
    for (Field field : fields) {
          if (field.isAnnotationPresent(Num.class)) {
               Num num= field.getAnnotation(Num.class);
               ……
          }
          ……
    }
    

    在网上找到了一张注解的提纲,非常详细,除了没有java 8里注解新特性,这里引用下:


    注解提纲

    讲了这么多,都是纯java和运行时注解的,下面开始结合Android Studio讲讲编译时注解


    APT

    讲编译时注解,先了解下注解处理器工具APT(Annotation Processing Tool)
       APT(Annotation processing tool)是一种处理注释的工具,它对源代码文件进行检测找出其中的Annotation,使用Annotation进行额外的处理。可以在编译时进行注解处理,也可以在运行时通过反射API进行注解处理。编译时进行注解处理是根据源文件中的Annotation生成额外的源文件和其它的文件,将它们一起生成class文件。
      使用APT主要的目的是简化开发者的工作量,因为APT可以编译程序源代码的同时,生成一些附属文件(比如源文件,类文件,程序发布描述文件等),这些附属文件的内容也都是与源代码相关的,换句话说,使用APT可以代替传统的对代码信息和附属文件的维护工作。
      
    下面将结合Android Studio实现编译时注解,主要内容来自这篇文章:THE 10-STEP GUIDE TO ANNOTATION PROCESSING IN ANDROID STUDIO。先看下项目的结构,如果是第一次尝试,包名最好先完全一样,省的哪里出错。

    项目.png
    1. 新建一个android项目 AnnotationProcessor,包名为com.stablekernel.annotationprocessor,再建一个Java Library 的module,如下图所示

      构建注解module
      并且设置下app模块依赖processor模块
      Paste_Image.png
    2. 设置兼容性

    • 在app 模块的gradle里添加
    compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_7
       targetCompatibility JavaVersion.VERSION_1_7
    }
    

    如下图所示:


    Paste_Image.png
    • 在processor 模块的gradle里添加
    sourceCompatibility = 1.7
    targetCompatibility = 1.7
    

    如下图所示:


    Paste_Image.png
    1. 在processor 模块里创建注解


      Paste_Image.png

      CustomAnnotation是自定义的注解,源码很简单:

    package com.stablekernel.annotationprocessor.processor;
    public @interface CustomAnnotation {
    }```
    
    4. 在processor 模块里创建注解处理器CustomAnnotationProcessor是注解处理器,源码如下:
    ```java
    @SupportedAnnotationTypes("com.stablekernel.annotationprocessor.processor.CustomAnnotation")
    @SupportedSourceVersion(SourceVersion.RELEASE_7)
    public class CustomAnnotationProcessor extends AbstractProcessor {
        @Override
        public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
            StringBuilder builder = new StringBuilder()
                    .append("package com.stablekernel.annotationprocessor.generated;\n\n")
                    .append("public class GeneratedClass {\n\n") // open class
                    .append("\tpublic String getMessage() {\n") // open method
                    .append("\t\treturn \"");
            // for each javax.lang.model.element.Element annotated with the CustomAnnotation
            for (Element element : roundEnv.getElementsAnnotatedWith(CustomAnnotation.class)) {
                String objectType = element.getSimpleName().toString();
                // this is appending to the return statement
                builder.append(objectType).append(" says hello!\\n");
            }
            builder.append("\";\n") // end return
                    .append("\t}\n") // close method
                    .append("}\n"); // close class
            try { // write the file
                JavaFileObject source = processingEnv.getFiler()
                       .createSourceFile("com.stablekernel.annotationprocessor.generated.GeneratedClass");
                Writer writer = source.openWriter();
                writer.write(builder.toString());
                writer.flush();
                writer.close();
            } catch (IOException e) {
                // Note: calling e.printStackTrace() will print IO errors
                // that occur from the file already existing after its first run, this is normal
            }
            return true;
        }
    }
    

    稍微解释下,注解器需要继承AbstractProcessor ,并且实现process方法,CustomAnnotationProcessor 类上面两个注解@SupportedAnnotationTypes 和@SupportedSourceVersion 分别表示支持的注解的类型和支持的版本,在process里面的StringBuilder 就是在编译时要创建的新文件里面的内容了,里面一个for循环是遍历了所有使用该CustomAnnotation.class注解的元素,取出其名字。最下面的try catch 里是将该文件写入source下, 编译成功后,具体位置如下图:


    Paste_Image.png
    1. 创建resources


      Paste_Image.png

      在processor 的main文件夹下 新建文件夹resources ,新建文件夹META-INF ,新建文件javax.annotation.processing.Processor。该文件里面的内容就是注解处理器的路径,如果有多个注解处理器,记得换行,每行写一个。


      Paste_Image.png
    2. 在全局的gradle里添加android-apt依赖,再在app 模块的gradle中添加插件。


      Paste_Image.png
      Paste_Image.png
    3. 设置构建依赖:


      Paste_Image.png

      或者

    dependencies {
       compile files('libs/processor.jar')
       ……
    }
    

    然后写个任务,使得processor.jar复制到app的lib下,和预构建的任务

    task processorTask(type: Copy) {
        from '../processor/build/libs/processor.jar'
        into 'libs/'
    }
    processorTask.dependsOn(':processor:build')
    preBuild.dependsOn(processorTask)
    

    app的gralde最终变成这样,供参考:

    Paste_Image.png

    到这里其实就已经结束了,最后为了验证下,在MainActivity中调用下就可以

    @CustomAnnotation
    public class MainActivity extends AppCompatActivity {
    
        @CustomAnnotation
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            showAnnotationMessage();
        }
    
        private void showAnnotationMessage() {
            GeneratedClass generatedClass = new GeneratedClass();
            String message = generatedClass.getMessage();
            // android.support.v7.app.AlertDialog
            new AlertDialog.Builder(this)
                    .setPositiveButton("Ok", null)
                    .setTitle("Annotation Processor Messages")
                    .setMessage(message)
                    .show();
        }
    }
    

    为了加深对编译时注解的理解,再推荐下这篇文章:ButterKnife源码分析

    相关文章

      网友评论

        本文标题:android 注解的使用

        本文链接:https://www.haomeiwen.com/subject/jdfyittx.html