APT浅尝

作者: 几行代码 | 来源:发表于2020-06-12 13:29 被阅读0次

    安卓中有很多注入框架,如 ButterKnife、ARouter等等,今天简单实现一个APT注入框架。
    首先创建对应的注解库(Java库): inject-annotation


    image.png

    简单定义一个注解 BindView。

    接下来创建一个安卓库,执行注入操作:inject


    image.png

    总共两个类:
    IBinder

    public interface IBinder<T> {
    
        /**
         * 绑定activity
         *
         * @param t
         */
        void bind(T t);
    
    }
    

    ViewBinder:

    public class ViewBinder {
        public static void bind(Object activity) {
            String name = activity.getClass().getName() + "_ViewBinding";
            try {
                Class<?> clazz = Class.forName(name);
                IBinder binder = (IBinder) clazz.newInstance();
                binder.bind(activity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    然后创建解析编译器:apt_compiler (Java库)这里使用的是谷歌的 auto-service
    build.gradle 文件

    apply plugin: 'java-library'
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation project(path: ':inject-annotation')
    
        // 注册APT功能
        annotationProcessor 'com.google.auto.service:auto-service:1.0-rc6'
        //noinspection AnnotationProcessorOnCompilePath
        compileOnly 'com.google.auto.service:auto-service:1.0-rc6'
    }
    
    sourceCompatibility = "1.7"
    targetCompatibility = "1.7"
    
    image.png

    编译注解处理类:AnnotationsCompiler

    package com.mobile.apt_compiler;
    
    import com.google.auto.service.AutoService;
    import com.mobile.inject_annotation.BindView;
    import java.io.*;
    import java.util.*;
    import javax.annotation.processing.*;
    import javax.lang.model.SourceVersion;
    import javax.lang.model.element.*;
    import javax.lang.model.type.TypeMirror;
    import javax.tools.JavaFileObject;
    
    /**
     * @author tony.wang
     * @time 2020/5/44
     * @description AnnotationsCompiler 编译注解
     */
    @AutoService(Processor.class)
    public class AnnotationsCompiler extends AbstractProcessor {
    
        // inject library 下 IBinder 的包名,这里写错编译的时候会报错
        private static final String PACKAGE_NAME_BINDER = "com.mobile.inject";
    
        /**
         * Java 文件输出类(非常重要)生成它是用来 java 文件
         */
        private Filer filer;
    
        /**
         * 支持的 Java 版本
         */
        @Override
        public SourceVersion getSupportedSourceVersion() {
            return SourceVersion.latestSupported();
        }
    
        /**
         * 支持的注解 当前注解处理器
         * 返回的是 set 字符串集合
         */
        @Override
        public Set<String> getSupportedAnnotationTypes() {
            Set<String> types = new HashSet<>();
            types.add(BindView.class.getCanonicalName());
            return types;
        }
    
        @Override
        public synchronized void init(ProcessingEnvironment processingEnvironment) {
            super.init(processingEnvironment);
            filer = processingEnvironment.getFiler();
        }
    
        /**
         * javac 编译器  遇到含有 BindView 注解的 java 文件时,就会调用这个 process 方法
         */
        @Override
        public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    
            Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindView.class);
    
            // 类:TypeElement
            // 方法:ExecutableElement
            // 属性:VariableElement
    
            Map<String, List<VariableElement>> map = new HashMap<>();
    
            for (Element element : elements) {
                VariableElement variableElement = (VariableElement) element;
                String activityName = variableElement.getEnclosingElement().getSimpleName().toString();
                List<VariableElement> variableElements = map.get(activityName);
                if (variableElements == null) {
                    variableElements = new ArrayList<>();
                    map.put(activityName, variableElements);
                }
                variableElements.add(variableElement);
            }
    
            if (map.size() > 0) {
                Writer writer = null;
                Iterator<String> iterator = map.keySet().iterator();
                while (iterator.hasNext()) {
                    String activityName = iterator.next();
                    List<VariableElement> variableElements = map.get(activityName);
    
                    //获取包名
                    TypeElement typeElement = (TypeElement) variableElements.get(0).getEnclosingElement();
                    String packageName = processingEnv.getElementUtils().getPackageOf(typeElement).toString();
    
                    try {
                        JavaFileObject sourceFile =
                                filer.createSourceFile(packageName + "." + activityName + "_ViewBinding");
                        writer = sourceFile.openWriter();
                        writer.write("package " + packageName + ";\n");
                        writer.write("import " + PACKAGE_NAME_BINDER + ".IBinder;\n");
                        writer.write("public class "+activityName+"_ViewBinding implements IBinder<"+packageName+"."+activityName+">{\n");
                        writer.write("@Override\n");
                        writer.write("public void bind("+packageName+"."+activityName+" target){\n");
                        for(VariableElement variableElement:variableElements) {
                            // 获取名字
                            String variableName = variableElement.getSimpleName().toString();
                            // 获取ID
                            int id = variableElement.getAnnotation(BindView.class).value();
                            // 得到类型
                            TypeMirror typeMirror = variableElement.asType();
                            writer.write("target."+variableName+"=("+typeMirror+")target.findViewById("+id+");\n");
                        }
                        writer.write("\n}\n}");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finally {
                        if(writer!=null)
                        {
                            try {
                                writer.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            return false;
        }
    }
    

    至此,准备工作已经做完了。
    测试一下:
    创建一个 Activity:

    public class MainActivity extends AppCompatActivity {
    
        @BindView(R.id.tv)
        TextView tv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // 调用自己定义的 ViewBinder
            ViewBinder.bind(this);
            tv.setText("Hi,ViewBinder!");
        }
    }
    
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    结果显示

    相关文章

      网友评论

          本文标题:APT浅尝

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