美文网首页
使用annotationProcessor打造编译时的注解(二)

使用annotationProcessor打造编译时的注解(二)

作者: lkkz | 来源:发表于2018-07-05 22:38 被阅读33次

    如果还没看如何搭建项目目录和设置断点调试的请移步第一篇
    使用annotationProcessor打造编译时的注解(一)

    参数对象方法说明

    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    return false;
    }
    
    • 参数Set<? extends TypeElement> set:表示使用了支持处理注解的节点集合,此处只支持了BindView,所以此处set集合中只有一个元素
    • RoundEnvironment roundEnvironment:表示当前或是之前的运行环境,可以通过该对象查找找到的注解
    • return 返回true为表示后续处理器不会再处理(已经处理)

    下面为process方法,相关的字段都已经注释好了

    private Map<String, List<Element>> classMap = new HashMap<>();
    
       @Override
        public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
            messager.printMessage(Diagnostic.Kind.NOTE, "process============");
            for (TypeElement typeElement : set) {
                messager.printMessage(Diagnostic.Kind.NOTE, "typeElement: " + typeElement.toString());
              //typeElement就相当于com.cool.butterknife.annoation.BindView
              //通过roundEnvironment来获取所有被BindView注解注解了的字段
                Set<? extends Element> elementsAnnotatedWith = roundEnvironment.getElementsAnnotatedWith(typeElement);
                for (Element element : elementsAnnotatedWith) {
                    //如果在MainActivity中有这段代码 @BindView(R.id.textView)TextView textView;
                   //此处的element就是TextView节点元素
                    //element.getEnclosingElement()为获取其父节点元素,即MainActivty
                    Element enclosingElement = element.getEnclosingElement();
                    TypeMirror classTypeMirror = enclosingElement.asType();
                    //className为MainActivty的全类名
                    String className = classTypeMirror.toString();
                    //上面只是拿MainActivty举个例子,但是真实的使用注解的可能还有SecondActivity等等,所有需要以类名为键保存里面所有使用了BindView注解的节点
                    List<Element> elements = classMap.get(className);
                    if (elements == null) {
                        elements = new ArrayList<>();
                        elements.add(element);
                        classMap.put(className, elements);
                    }else {
                        elements.add(element);
                    }
                }
    
                Set<Map.Entry<String, List<Element>>> entries = classMap.entrySet();
                for (Map.Entry<String, List<Element>> entry : entries) {
                    String key = entry.getKey();
                    List<Element> value = entry.getValue();
                  //生成java代码
                    generateViewBinding(key,value);
                }
    
            }
            return false;
        }
    

    generateViewBinding方法

    首先看一下生成的2个类中的代码

    public class MainActivity_ViewBinding implements Unbinder {
      private MainActivity target;
    
      @UiThread
      public MainActivity_ViewBinding(final MainActivity target, View source) {
        this.target = target;
        target.textView = source.findViewById(2131165320);
        target.textView2 = source.findViewById(2131165321);
      }
    
      public void unbind() {
        MainActivity target = this.target;
        this.target = null;
        target.textView = null;
        target.textView2 = null;
      }
    }
    
    public class SecondActivity_ViewBinding implements Unbinder {
      private SecondActivity target;
    
      @UiThread
      public SecondActivity_ViewBinding(final SecondActivity target, View source) {
        this.target = target;
        target.button = source.findViewById(2131165219);
      }
    
      public void unbind() {
        SecondActivity target = this.target;
        this.target = null;
        target.button = null;
      }
    }
    

    生成代码使用了 javapoet,没用过不懂的可以参考其github主页上的例子

    private void generateViewBinding(String key, List<Element> values) {
            //生成类元素节点 此处key为com.cool.butterknife.MainActivity或者com.cool.butterknife.SecondActivity
            TypeElement classTypeElement = elementUtils.getTypeElement(key);
            //生成参数 final MainActivity target
            ParameterSpec targetParameterSpec = ParameterSpec
                    .builder(ClassName.get(classTypeElement), "target", Modifier.FINAL)
                    .build();
            //生成参数  View source
            ParameterSpec viewParameterSpec = ParameterSpec.builder(ClassName.get("android.view", "View"), "source")
                    .build();
            MethodSpec constructor = null;
    
            //生成构造函数
            MethodSpec.Builder constructorMethodBuilder = MethodSpec.constructorBuilder()
                    .addParameter(targetParameterSpec)
                    .addParameter(viewParameterSpec)
                    .addAnnotation(ClassName.bestGuess("android.support.annotation.UiThread"))
                    .addModifiers(Modifier.PUBLIC);
    
            //  构造函数中添加代码块
            constructorMethodBuilder.addStatement("this.target = target");
            for (Element element : values) {
                BindView bindView = element.getAnnotation(BindView.class);
    
                int id = bindView.value();
                Name simpleName = element.getSimpleName();
                constructorMethodBuilder.addStatement("target.$L = source.findViewById($L)", simpleName.toString(), id);
            }
            constructor = constructorMethodBuilder.build();
    
            //生成unbind方法
            MethodSpec.Builder unbindMethodSpec = MethodSpec.methodBuilder("unbind")
                    .addModifiers(Modifier.PUBLIC);
            unbindMethodSpec.addStatement("$T target = this.target", ClassName.get(classTypeElement));
            unbindMethodSpec.addStatement("this.target = null");
    
            for (Element element : values) {
                Name simpleName = element.getSimpleName();
                unbindMethodSpec.addStatement("target.$L = null", simpleName.toString());
            }
    
            //生成MainActivity_ViewBinding类
            TypeSpec typeSpec = TypeSpec.classBuilder(classTypeElement.getSimpleName() + "_ViewBinding")
                    .addField(ClassName.get(classTypeElement), "target", Modifier.PRIVATE)
                    .addMethod(constructor)
                    .addMethod(unbindMethodSpec.build())
                    .addSuperinterface(ClassName.bestGuess("com.cool.butterknife.core.Unbinder"))
                    .addModifiers(Modifier.PUBLIC)
                    .build();
    
            //获取包名
            String packageName = elementUtils.getPackageOf(classTypeElement).getQualifiedName().toString();
            messager.printMessage(Diagnostic.Kind.NOTE, "packageName: " + packageName.toString());
            JavaFile javaFile = JavaFile.builder(packageName, typeSpec)
                    .build();
    
            try {
                //写入java文件
                javaFile.writeTo(filer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

    看完,你可能会有点身体不适,但是这个难点在于如何拼接类,有点繁琐,一不小心就容易出错,而且出错之后问题比较难找,唯有静下心来慢慢的看,一定要仔细。

    到处,点击make就可以生成类了,接下来使用刚刚生成的类

    /**
     * Created by cool on 2018/7/3.
     */
    public class Butterknife {
    
        static final Map<Class<?>, Constructor<? extends Unbinder>> BINDINGS = new LinkedHashMap<>();
    
        @NonNull
        @UiThread
        public static Unbinder bind(@NonNull Activity target) {
            View sourceView = target.getWindow().getDecorView();
            return createBinding(target, sourceView);
        }
    
        private static Unbinder createBinding(Activity target, View sourceView) {
            Class<?> targetClass = target.getClass();
            Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass);
            if (constructor == null) {
                return Unbinder.EMPTY;
            }
            try {
                return constructor.newInstance(target, sourceView);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Unable to invoke " + constructor, e);
            } catch (InstantiationException e) {
                throw new RuntimeException("Unable to invoke " + constructor, e);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                }
                if (cause instanceof Error) {
                    throw (Error) cause;
                }
                throw new RuntimeException("Unable to create binding instance.", cause);
            }
        }
    
        private static Constructor<? extends Unbinder> findBindingConstructorForClass(Class<?> targetClass) {
            Constructor<? extends Unbinder> constructor = BINDINGS.get(targetClass);
            if (constructor != null) {
                return constructor;
            }
    
            String targetClassName = targetClass.getName();
            try {
                Class<?> viewBindingClass = Class.forName(targetClassName + "_ViewBinding");
                constructor = (Constructor<? extends Unbinder>) viewBindingClass.getConstructor(targetClass, View.class);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            BINDINGS.put(targetClass, constructor);
    
            return constructor;
        }
    }
    

    呃呃,这个就不解释类,比较简单,接下来是使用

    public class MainActivity extends AppCompatActivity {
    
        @BindView(R.id.textView)
        TextView textView;
    
        @BindView(R.id.textView2)
        TextView textView2;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Butterknife.bind(this);
            textView.setText("ButterKnife Test");
        }
    
        @OnClick(R.id.bt_click)
        public void onClick(View view){
            Toast.makeText(this,"点击",Toast.LENGTH_SHORT).show();
        }
    }
    

    最后贴一下BindViewProcessor.java完整版

    package com.cool.butterknife.compiler;
    
    import com.cool.butterknife.annoation.BindView;
    import com.google.auto.service.AutoService;
    import com.squareup.javapoet.ClassName;
    import com.squareup.javapoet.JavaFile;
    import com.squareup.javapoet.MethodSpec;
    import com.squareup.javapoet.ParameterSpec;
    import com.squareup.javapoet.TypeSpec;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    import javax.annotation.processing.AbstractProcessor;
    import javax.annotation.processing.Filer;
    import javax.annotation.processing.Messager;
    import javax.annotation.processing.ProcessingEnvironment;
    import javax.annotation.processing.Processor;
    import javax.annotation.processing.RoundEnvironment;
    import javax.annotation.processing.SupportedAnnotationTypes;
    import javax.annotation.processing.SupportedSourceVersion;
    import javax.lang.model.SourceVersion;
    import javax.lang.model.element.AnnotationMirror;
    import javax.lang.model.element.AnnotationValue;
    import javax.lang.model.element.Element;
    import javax.lang.model.element.ExecutableElement;
    import javax.lang.model.element.Modifier;
    import javax.lang.model.element.Name;
    import javax.lang.model.element.TypeElement;
    import javax.lang.model.element.VariableElement;
    import javax.lang.model.type.TypeMirror;
    import javax.lang.model.util.Elements;
    import javax.tools.Diagnostic;
    
    @AutoService(Processor.class)
    @SupportedAnnotationTypes("com.cool.butterknife.annoation.BindView")
    @SupportedSourceVersion(SourceVersion.RELEASE_7)
    public class BindViewProcessor extends AbstractProcessor {
    
        private Messager messager;
        private Filer filer;
        private Elements elementUtils;
        private Map<String, List<Element>> classMap = new HashMap<>();
    
        @Override
        public synchronized void init(ProcessingEnvironment processingEnvironment) {
            super.init(processingEnvironment);
            filer = processingEnvironment.getFiler();
            messager = processingEnvironment.getMessager();
            elementUtils = processingEnvironment.getElementUtils();
            messager.printMessage(Diagnostic.Kind.NOTE, "=========init============");
        }
    
        @Override
        public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
            messager.printMessage(Diagnostic.Kind.NOTE, "=======process============");
            for (TypeElement typeElement : set) {
                messager.printMessage(Diagnostic.Kind.NOTE, "typeElement: " + typeElement.toString());
                //typeElement就相当于com.cool.butterknife.annoation.BindView
                //通过roundEnvironment来获取所有被BindView注解注解了的字段
                Set<? extends Element> elementsAnnotatedWith = roundEnvironment.getElementsAnnotatedWith(typeElement);
                for (Element element : elementsAnnotatedWith) {
                    //如果在MainActivity中有这段代码 @BindView(R.id.textView)TextView textView;
                    //此处的element就是TextView节点元素
                    //element.getEnclosingElement()为获取其父节点元素,即MainActivty
                    Element enclosingElement = element.getEnclosingElement();
                    TypeMirror classTypeMirror = enclosingElement.asType();
                    //className为MainActivty的全类名
                    String className = classTypeMirror.toString();
                    //上面只是拿MainActivty举个例子,但是真实的使用注解的可能还有SecondActivity等等,所有需要以类名为键保存里面所有使用了BindView注解的节点
                    List<Element> elements = classMap.get(className);
                    if (elements == null) {
                        elements = new ArrayList<>();
                        elements.add(element);
                        classMap.put(className, elements);
                    } else {
                        elements.add(element);
                    }
                }
    
                Set<Map.Entry<String, List<Element>>> entries = classMap.entrySet();
                for (Map.Entry<String, List<Element>> entry : entries) {
                    String key = entry.getKey();
                    List<Element> value = entry.getValue();
                    //生成java代码
                    generateViewBinding(key, value);
                }
    
            }
            return false;
        }
    
        private void generateViewBinding(String key, List<Element> values) {
            //生成类元素节点 此处key为com.cool.butterknife.MainActivity或者com.cool.butterknife.SecondActivity
            TypeElement classTypeElement = elementUtils.getTypeElement(key);
            //生成参数 final MainActivity target
            ParameterSpec targetParameterSpec = ParameterSpec
                    .builder(ClassName.get(classTypeElement), "target", Modifier.FINAL)
                    .build();
            //生成参数  View source
            ParameterSpec viewParameterSpec = ParameterSpec.builder(ClassName.get("android.view", "View"), "source")
                    .build();
            MethodSpec constructor = null;
    
            //生成构造函数
            MethodSpec.Builder constructorMethodBuilder = MethodSpec.constructorBuilder()
                    .addParameter(targetParameterSpec)
                    .addParameter(viewParameterSpec)
                    .addAnnotation(ClassName.bestGuess("android.support.annotation.UiThread"))
                    .addModifiers(Modifier.PUBLIC);
    
            //  构造函数中添加代码块
            constructorMethodBuilder.addStatement("this.target = target");
            for (Element element : values) {
                BindView bindView = element.getAnnotation(BindView.class);
    
                int id = bindView.value();
                Name simpleName = element.getSimpleName();
                constructorMethodBuilder.addStatement("target.$L = source.findViewById($L)", simpleName.toString(), id);
            }
            constructor = constructorMethodBuilder.build();
    
            //生成unbind方法
            MethodSpec.Builder unbindMethodSpec = MethodSpec.methodBuilder("unbind")
                    .addModifiers(Modifier.PUBLIC);
            unbindMethodSpec.addStatement("$T target = this.target", ClassName.get(classTypeElement));
            unbindMethodSpec.addStatement("this.target = null");
    
            for (Element element : values) {
                Name simpleName = element.getSimpleName();
                unbindMethodSpec.addStatement("target.$L = null", simpleName.toString());
            }
    
            //生成MainActivity_ViewBinding类
            TypeSpec typeSpec = TypeSpec.classBuilder(classTypeElement.getSimpleName() + "_ViewBinding")
                    .addField(ClassName.get(classTypeElement), "target", Modifier.PRIVATE)
                    .addMethod(constructor)
                    .addMethod(unbindMethodSpec.build())
                    .addSuperinterface(ClassName.bestGuess("com.cool.butterknife.core.Unbinder"))
                    .addModifiers(Modifier.PUBLIC)
                    .build();
    
            //获取包名
            String packageName = elementUtils.getPackageOf(classTypeElement).getQualifiedName().toString();
            messager.printMessage(Diagnostic.Kind.NOTE, "packageName: " + packageName.toString());
            JavaFile javaFile = JavaFile.builder(packageName, typeSpec)
                    .build();
    
            try {
                //写入java文件
                javaFile.writeTo(filer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    onClick在写这篇文章时没做实现,到时实现放在第3篇吧
    查看源码
    使用annotationProcessor打造编译时的注解(三)

    相关文章

      网友评论

          本文标题:使用annotationProcessor打造编译时的注解(二)

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