• Android APT实现,SqInject的实现原理


    一、APT技术简介

    1、APT定义

    APT(Annotation Processing Tool)即注解处理器,是一种处理注解的工具,确切的说它是javac的一个工具,它用来在编译时扫描和处理注解。注解处理器以Java代码作为输入,生成.java文件作为输出

    2、注解定义

    1、注解是一种能被添加到java代码中的元数据,类、方法、变量、参数和包都可以用注解修饰。

    2、注解对于它所修饰的代码没有直接的影响

    3、APT原理简介

    Annotation processing是在编译阶段执行的,它的原理就是读入Java源代码,解析注解,然后生成新的Java代码。新生成的Java代码最后被编译成Java字节码,注解解析器(Annotation Processor)不能改变读入的Java 类,比如不能加入或删除Java方法

    二、APT实战使用

    1、SqInject框架来源

    在手游发行中,经常需要切包,将游戏接完SDK1的包,通过反编译,替换smali文件及其他资源文件的方式,替换为渠道SDK2的渠道包。在这个反编译回编译的过程中,资源索引ID(即R类和resources.arsc中的ID映射关系)会发生冲突导致程序异常,即不做特殊处理的话,渠道SDK及发行SDK是不能直接使用R类的,要使用getIdentifier获取资源ID

    要求在程序中使用getIdentifier,在开发过程中是比较麻烦的事情。在这样的条件下,我们也无法使用如butterknife这样的框架。因此,我们模仿butterknife开发了一套基于getIdentifier的控件注入框架SqInject。下面介绍SqInject的实现,先来看下简单使用哈

    2、SqInject的实现原理

    public class MainActivity extends AppCompatActivity {
      
     //绑定ID
     @BindView(SqR.id.tv)
     TextView hello;
     
     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     SqInject.bind(this);
     Log.e("SqInject", hello.getText().toString());
     }
     
     //绑定点击事件
     @OnClick(SqR.id.tv)
     public void click(View view) {
     Intent intent = new Intent(MainActivity.this, TestActivity.class);
     startActivity(intent);
     }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    2.1、注解处理器模块实现

    上文说到APT常用于生成代码,在SqInject中APT注解处理环节中,流程如下图所示:

    在编译过程中扫描注解,生成Java代码,而后再次编译

    在SqInject代码中,实现如下:

    @AutoService(Processor.class)
    @SupportedSourceVersion(SourceVersion.RELEASE_7)
    public class SqInjectProcessor extends AbstractProcessor {
     
     ...
      
     //核心方法
     @Override
     public boolean process(Set set, RoundEnvironment roundEnvironment) {
     //控件类注解解析,ResChecker检查资源id合法性,合法则生成"类名+$ViewBinder类,否则编译失败
     BindViewBuilder bindViewBuilder = new BindViewBuilder(roundEnvironment, mResChecker, mElementUtils, mTypeUtils, mFiler, mMessager);
     bindViewBuilder.build();
     //id类注解解析,ResChecker检查资源id合法性,合法则生成"类名+$IdBinder类",否则编译失败
     BindIdsBuilder bindIdsBuilder = new BindIdsBuilder(roundEnvironment, mResChecker, mElementUtils, mTypeUtils, mFiler, mMessager);
     bindIdsBuilder.build();
     return false;
     }
    
    
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在生成控件注入相关代码之前,框架中会先检测资源id的合法性,本框架中在使用注解时,传入的是字符串。可资源名称是有可能不存在对应资源的,框架会做相应的检测

    2.2、资源检测

    Android编译资源过程中,会生成R类,也就是说只有在R类中存在的,用getIdentifier才能够获取到,那么我们可以用R类来检测传入的参数是否合理,代码如下:

    /**
     * 检测资源id在R文件中是否存在
     * @param name
     * @param type
     * @return
     */
     public boolean isIdValid(String name, String type) {
     String RClassName = mPackageNeme + ".R." + type;
     TypeElement RClassType = mElementUtils.getTypeElement(RClassName);
     if (RClassType == null) {
     mMessager.printMessage(Diagnostic.Kind.ERROR, RClassName + "不存在,请检查是否包名有误,或者类型错误");
     } else {
     //遍历属性
     for (Element element : RClassType.getEnclosedElements()) {
     String fieldName = element.getSimpleName().toString();
     if (name.equals(fieldName)) {
     return true;
     }
     }
     }
     return false;
     } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    2.3、解析注解,生成代码

    以解析BindView为例,代码如下:

    /**
     * 解析BindView注解
     * @return
     */
     private Map> parseBindView(){
     Set elements = (Set) mRoundEnvironment.getElementsAnnotatedWith(BindView.class);
     if (!Utils.isEmpty(elements)) {
     Map> map = new HashMap<>();
     for (Element element : elements) {
     if (element instanceof VariableElement) {
     //获取该属性所在类
     TypeElement targetElement = (TypeElement) element.getEnclosingElement();
     mTargetSet.add(targetElement);
     if (map.get(targetElement) == null) {
     List targetStringLists = new ArrayList<>();
     targetStringLists.add((VariableElement) element);
     map.put(targetElement, targetStringLists);
     } else {
     map.get(targetElement).add((VariableElement) element);
     }
     }
     }
     return map;
     }
     return null;
     } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    解析完BindView注解后,使用javapoet生成代码,篇幅有限,下面仅列出获取参数和生成代码的一小部分

    if (mBindViewIdTargetMap != null && mBindViewIdTargetMap.get(targetElement) != null) {
     List viewElements = mBindViewIdTargetMap.get(targetElement);
     //方法体
     for (VariableElement viewElement : viewElements) {
     //获取属性名
     String fieldName = viewElement.getSimpleName().toString();
     //获取类型
     TypeMirror typeMirror = viewElement.asType();
     TypeElement fieldClassElement = (TypeElement) mTypeUtils.asElement(typeMirror);
     mMessager.printMessage(Diagnostic.Kind.NOTE, "注解的字段类型为: " + fieldClassElement.getQualifiedName().toString());
     TypeElement fieldType = mElementUtils.getTypeElement(fieldClassElement.getQualifiedName());
     ClassName fieldClassName = ClassName.get(fieldType);
     //获取@BindView注解的值,即名称
     String name = viewElement.getAnnotation(BindView.class).value();
     //检测名称是否合法
     if(!mResChecker.isIdValid(name, "id")){
     mMessager.printMessage(Diagnostic.Kind.ERROR, "R文件中不存在id为" + name + "的值");
     }
     methodBuilder.addStatement("target.$N = $T.findRequiredViewAsType(source, $S, $S, $T.class)", fieldName, JptConstants.UTILS, name, "field " + fieldName,fieldClassName);
     }
     } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    小小总结一下,在注解处理器中,最重要的两个环节,一个是解析注解,获取参数,然后是利用javapoet框架生成代码

    下面看下生成的代码

    public class MainActivity$ViewBinder implements ViewBinder {
     @Override
     public void bindView(final MainActivity target, final View source) {
     //这里就是上面的代码生成的
     target.hello = ViewUtils.findRequiredViewAsType(source, "tv", "field hello", TextView.class);
     IdUtils.findViewByName("tv", source).setOnClickListener(new DebouncingOnClickListener() {
     public void doClick(View v) {
     target.click(v);
     }
     } );
     }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    到这里,就介绍完了使用APT生成代码了更多Android开发的进阶技术,可以参考《Android核心技术手册》点击可查看详细类目。

  • 相关阅读:
    用Python绘制简单曲线的几个方法
    操作系统的基本概念
    R-FCN: Object Detection via Region-based Fully Convolutional Networks
    开发工具系列IDEA:配置注释自动生成
    轮式联合收割机液压系统设计
    【软件与系统安全笔记】三、基础技术
    Chimera:混合的 RLWE-FHE 方案
    从零开始操作系统-09:键盘实现
    HTML5期末大作业:基于 html css js仿腾讯课堂首页
    Day743.CPU结构影响Redis的性能问题 -Redis 核心技术与实战
  • 原文地址:https://blog.csdn.net/m0_70748845/article/details/133682740