美文网首页
Annotation

Annotation

作者: pphdsny | 来源:发表于2017-10-31 09:30 被阅读13次

    Annotation

    概念

    @Documented –注解是否将包含在JavaDoc中
    @Retention –什么时候使用该注解

    • RetentionPolicy.SOURCE – 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@Override, @SuppressWarnings都属于这类注解。
    • RetentionPolicy.CLASS – 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式。
    • RetentionPolicy.RUNTIME– 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。

    @Target? –注解用于什么地方

    • ElementType.TYPE:用于描述类、接口或enum声明
    • ElementType.FIELD:用于描述实例变量
    • ElementType.METHOD:方法
    • ElementType.PARAMETER:方法参数
    • ElementType.CONSTRUCTOR:构造方法
    • ElementType.LOCAL_VARIABLE:局部变量
    • ElementType.ANNOTATION_TYPE 另一个注释
    • ElementType.PACKAGE 用于记录java文件的package信息

    @Inherited – 是否允许子类继承该注解

    Annotations只支持基本类型、String及枚举类型。注释中所有的属性被定义成方法,并允许提供默认值。

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @interface Todo {
        public enum Priority {LOW, MEDIUM, HIGH}
        public enum Status {STARTED, NOT_STARTED}
        String author() default "Yash";
        Priority priority() default Priority.LOW;
        Status status() default Status.NOT_STARTED;
    }
    
    //Sample
    @Todo(priority = Todo.Priority.MEDIUM, author = "Yashwant", status = Todo.Status.STARTED)
    public void incompleteMethod1() {
    //Some business logic is written
    //But it’s not complete yet
    }
    

    如何使用

    我们需要使用反射机制。如果你熟悉反射代码,就会知道反射可以提供类名、方法和实例变量对象。所有这些对象都有getAnnotation()这个方法用来返回注解信息。我们需要把这个对象转换为我们自定义的注释(使用 instanceOf()检查之后),同时也可以调用自定义注释里面的法方

    Class businessLogicClass = BusinessLogic.class;
    for(Method method : businessLogicClass.getMethods()) {
        Todo todoAnnotation = (Todo)method.getAnnotation(Todo.class);
        if(todoAnnotation != null) {
            System.out.println(" Method Name : " + method.getName());
            System.out.println(" Author : " + todoAnnotation.author());
            System.out.println(" Priority : " + todoAnnotation.priority());
            System.out.println(" Status : " + todoAnnotation.status());
        }
    }
    

    APT

    APT(Annotation Processing Tool)是javac内置的工具,用于在编译时期扫描和处理注解信息。

    实现步骤

    1. 新建一个Java Project(因为AbstractProcessor是sun java中的,Android中并没有这个类)

    2. 定义一个注解

      @Target({ElementType.FIELD, ElementType.METHOD})
      @Retention(RetentionPolicy.RUNTIME)
      public @interface ViewInject {
          int value();
      }
      
    3. 定义一个新的类继承AbstractProcessor

      // 支持的注解类型, 此处要填写全类名
      @SupportedAnnotationTypes("com.example.annotation.ViewInject")
      // JDK版本,Java8会有问题,待解决***
      @SupportedSourceVersion(SourceVersion.RELEASE_7)
      public class ViewInjectProcessor extends AbstractProcessor {
      
          @Override
          public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv){
               /** 
               * annotations 表示待处理的 Annotations
               * roundEnv 表示当前或是之前的运行环境
               * 返回值 其他processor是否要处理,retur false在Android中才能被生成代码
               */
               for (TypeElement te : annotations) {
                  for (Element e : roundEnv.getElementsAnnotatedWith(te)) {
                      // 准备在gradle的控制台打印信息
                      Messager messager = processingEnv.getMessager();
                      // 打印
                      messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + e.toString());
                      messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + e.getSimpleName());
                      messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + e.getEnclosingElement().toString());
      
                      // 获取注解
                      ViewInject annotation = e.getAnnotation(ViewInject.class);
      
                      // 获取元素名并将其首字母大写
                      String name = e.getSimpleName().toString();
                      char c = Character.toUpperCase(name.charAt(0));
                      name = String.valueOf(c + name.substring(1));
      
                      // 包裹注解元素的元素, 也就是其父元素, 比如注解了成员变量或者成员函数, 其上层就是该类
                      Element enclosingElement = e.getEnclosingElement();
                      // 获取父元素的全类名, 用来生成包名
                      String enclosingQualifiedName;
                      if (enclosingElement instanceof PackageElement) {
                          enclosingQualifiedName = ((PackageElement) enclosingElement).getQualifiedName().toString();
                      } else {
                          enclosingQualifiedName = ((TypeElement) enclosingElement).getQualifiedName().toString();
                      }
                      try {
                          // 生成的包名
                          String genaratePackageName = enclosingQualifiedName.substring(0, enclosingQualifiedName.lastIndexOf('.'));
                          // 生成的类名
                          String genarateClassName = PREFIX + enclosingElement.getSimpleName() + SUFFIX;
      
                          // 创建Java文件
                          JavaFileObject f = processingEnv.getFiler().createSourceFile(genarateClassName);
                          // 在控制台输出文件路径
                          messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + f.toUri());
                          Writer w = f.openWriter();
                          try {
                              PrintWriter pw = new PrintWriter(w);
                              pw.println("package " + genaratePackageName + ";");
                              pw.println("\npublic class " + genarateClassName + " { ");
                              pw.println("\n    /** 打印值 */");
                              pw.println("    public static void print" + name + "() {");
                              pw.println("        // 注解的父元素: " + enclosingElement.toString());
                              pw.println("        System.out.println(\"代码生成的路径: " + f.toUri() + "\");");
                              pw.println("        System.out.println(\"注解的元素: " + e.toString() + "\");");
                              pw.println("        System.out.println(\"注解的值: " + annotation.value() + "\");");
                              pw.println("    }");
                              pw.println("}");
                              pw.flush();
                          } finally {
                              w.close();
                          }
                      } catch (IOException x) {
                          processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                                  x.toString());
                      }
                  }
               return false;
          }
      }
      
    4. 向JVM申明解析器

      我们的解析器虽然定义好了, 但是jvm并不知道, 也不会调用, 因此我们需要声明.

      在java的同级目录新建resources目录, 新建META-INF/services/javax.annotation.processing.Processor文件, 文件中填写你自定义的Processor全类名

      //javax.annotation.processing.Processor
      com.example.annotation.ViewInjectProcessor
      

      上述实现十分不方便

      ***待验证

      google提供了一个注册处理器的库

      compile ‘com.google.auto.service:auto-service:1.0-rc2‘
      

      一个注解搞定:

      @AutoService(Processor.class)
      public class MyProcessor extends AbstractProcessor {}
      
    5. 将Java Project打包成为lib,在Android项目中引用

      AS打jar包参考

    6. 在Android项目中使用apt

      项目根目录gradle中buildscriptdependencies添加

      classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
      

      app目录的gradle中, 添加

      apply plugin: 'android-apt'
      
    7. 项目中使用相关注解

      生成代码的路径:/build/generated/source/apt/debug/yourpackagename

    debug Processor

    http://www.jianshu.com/p/80a14bc35000

    相关文章

      网友评论

          本文标题:Annotation

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