编译注解 ---实例

这个 demo 是这篇博客里的一个例子,光看没看懂,又照着写了一遍也还是很懵,为了更好的理解,几乎把每一句核心代码都打印,都注释了,这样才略懂了一些在编译时生成代码这个流程。

下面这个方法是最懵的,所以注释写了很多,里面的各种元素都比较抽象,看的时候,甚至是第一次写的时候,都不知道在写什么,通过打印把抽象的东西,还原成我们熟悉的东西就好理解多了。

    /**
     *
     * @param set  包含的是所有使用的[注解的信息],例如BindView,ContentView
     * @param roundEnvironment 返回的是所有被注解的[元素],例如类,属性等
     * @return
     */
    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
//        mMessager.printMessage(Diagnostic.Kind.NOTE,"process...");

        // 防止处理多次,要清空
        mProxyMap.clear();

        System.out.println("mProxyMap"+mProxyMap.toString());
        // 获取全部的带有 bindview 注解的 element
        Set<? extends Element> elseWithBind = roundEnvironment.getElementsAnnotatedWith(BindView.class);
        System.out.println("elseWithBind: " + elseWithBind.toString());
        //elseWithBind: [mTextView, mImageView]

        // 对bindview 进行循环,构建 proxyInfo 信息
        for (Element element : elseWithBind) {
            // 检查 element 的合法性
            checkSAnnotationValid(element,BindView.class);

            // 强转成属性元素
            VariableElement variableElement = (VariableElement) element;
            System.out.println("variableElement: "+variableElement);
//            variableElement: mTextView

            System.out.println("-----"+ element.getEnclosingElement());

            // 要获取类元素的类名,直接用 element 也可以,强转不是必须的。
            // 属性元素的外层一定是类元素
            TypeElement typeElement = (TypeElement) variableElement.getEnclosingElement();
            System.out.println("typeElement: "+typeElement);
            // typeElement: com.limiao.annotationdemo.MainActivity

            // 获取类元素的类名(全路径名)
            String fqClassName = typeElement.getQualifiedName().toString();
            System.out.println("fqClassName: "+fqClassName);
//            fqClassName: com.limiao.annotationdemo.MainActivity

            System.out.println("mProxyMap: "+mProxyMap);

            ProxyInfo proxyInfo = mProxyMap.get(fqClassName);
            if (proxyInfo == null){
                proxyInfo = new ProxyInfo(mElementUtils,typeElement);
                // 以 class 名称为 key,保存到 mProxy 中
                mProxyMap.put(fqClassName,proxyInfo);
            }

            System.out.println("proxyInfo:"+proxyInfo);

            // 获取 bindview 注解,把信息放入 proxyInfo 中
            BindView bindAnnotation = element.getAnnotation(BindView.class);
            int id = bindAnnotation.value();
            mMessager.printMessage(Diagnostic.Kind.NOTE,"proxyInfo:" + proxyInfo.toString());
            mMessager.printMessage(Diagnostic.Kind.NOTE,"variableElement:" + variableElement);
            mMessager.printMessage(Diagnostic.Kind.NOTE,"id:" + id);
            // 上面的强转要用到这里,作为参数
            proxyInfo.injectVarialbles.put(id,variableElement);
        }

        // 获取所有的 ContentView 注解,操作原理和上面的 bindview 一样
        Set<? extends Element> contentAnnotations = roundEnvironment.getElementsAnnotatedWith(ContentView.class);
        for (Element element : contentAnnotations) {
            TypeElement typeElement = (TypeElement) element;
            String fqClassName  = typeElement.getQualifiedName().toString();
            ProxyInfo proxyInfo = mProxyMap.get(fqClassName);
            if (proxyInfo == null) {
                proxyInfo = new ProxyInfo(mElementUtils,typeElement);
                mProxyMap.put(fqClassName,proxyInfo);
            }
            ContentView contentViewAnnotation = element.getAnnotation(ContentView.class);
            proxyInfo.contentViewId = contentViewAnnotation.value();
        }

        // 循环生成源文件
        for (String key : mProxyMap.keySet()) {
            ProxyInfo proxyInfo = mProxyMap.get(key);
            try {
                System.out.println("ProxyClassFullName: "+proxyInfo.getProxyClassFullName());
                System.out.println("TypeElement: "+proxyInfo.getTypeElement());
                // 创建一个 javaFile 文件
                // 第一个参数:创建的文件名,包含全路径
                // 第二个参数:与此文件的创建有因果关联的类型或包或模块元素,可以为null(文档的说明)
//                JavaFileObject jfo = processingEnv.getFiler().createSourceFile(proxyInfo.getProxyClassFullName(),proxyInfo.getTypeElement());
//                试了一下,如果第二个参数为 null ,也没有关系,还能正常编译运行
                JavaFileObject jfo = processingEnv.getFiler().createSourceFile(proxyInfo.getProxyClassFullName(),null);
                Writer writer = jfo.openWriter();
                writer.write(proxyInfo.generateJavaCode());
                writer.flush();
                writer.close();
            } catch (IOException e) {

                e.printStackTrace();
                error(proxyInfo.getTypeElement(),"unable to write injector for type %s: %s",proxyInfo.getTypeElement(),e.getMessage());
            }
        }

        return true;

    }

参考的这篇博客的作者关于编译注解写了一个系列的文章,都很好,这里整理一下贴出来,方便查阅。

深入理解编译注解(一)从实战理解什么是编译注解

深入理解编译注解(二)annotationProcessor与android-apt

深入理解编译注解(三)依赖关系 apt/annotationProcessor与Provided的区别

深入理解编译注解(四)常用接口介绍

深入理解编译注解(五)RetentionPolicy.SOURCE 和 RetentionPolicy.CLASS区别讨论

深入理解编译注解(六)Butterknife的实现原理

demo github 地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值