针对上篇讲的module之间的跳转问题, 这就出现了路由的概念了,应该上路由去帮助我们去做那些事
APT(Annatotion Processing Tool)
是一种处理注解的工具,它对源代码文件进行检测找出其中的注解(Annotation) 根据注解自动生成代码,如果想要自定义的注解处理器能够正常运行,必须要通过APT工具进行处理,也可以这么理解, 只有通过APT工具后,程序在编译期间注解解释器才能执行
通俗理解 根据规则 帮我们生成代码 生成类文件
现在动手来实现,新建个项目 APTTest
APT是注解处理器,那么先写个注解,创建一个java library 叫annotation,存放注解的,
package com.example.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS) // 要在编译时进行一些预处理操作。注解会在class文件中存在
public @interface ARouter {
String path();
String group() default "";
}
annotation library如下目录
然后在app中引入这个library
// 依赖注解
implementation project(':annotation')
再创建一个java library 注解处理器 compiler 这个是专门处理注解的
看下compiler中的build.gradle中配置
apply plugin: 'java-library'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
// As-3.4.1 + gradle5.1.1-all + auto-service:1.0-rc4
compileOnly'com.google.auto.service:auto-service:1.0-rc4'
annotationProcessor'com.google.auto.service:auto-service:1.0-rc4'
// 引入annotation,让注解处理器-处理注解
implementation project(':annotation')
}
// java控制台输出中文乱码
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
//jdk编译的版本是1.7
sourceCompatibility = "7"
targetCompatibility = "7"
其中
compileOnly'com.google.auto.service:auto-service:1.0-rc4'
annotationProcessor'com.google.auto.service:auto-service:1.0-rc4'
是Google给我们提供的注解处理器的一种服务,会生成一个文件,在build目录下生成文件
当然上面也引入了annotation 因为要处理这里的注解
现在在compiler中写个注解处理器类ARouterProcessor用来处理ARouter注解的,它继承此AbstractProcessor
在这个自定义的类上要添加几个注解
// AutoService则是固定的写法,加个注解即可
// 通过auto-service中的@AutoService可以自动生成AutoService注解处理器,用来注册
// 用来生成 META-INF/services/javax.annotation.processing.Processor 文件
@AutoService(Processor.class)
// 允许/支持的注解类型,让注解处理器处理(新增annotation module)
@SupportedAnnotationTypes({"com.example.annotation.ARouter"})
// 指定JDK编译版本
@SupportedSourceVersion(SourceVersion.RELEASE_7)
// 注解处理器接收的参数
@SupportedOptions("content")
代码中使用