APT,Annotation Processing Tool,注解处理器,是一种处理注解的工具,他在编译时扫描和处理注解,生成.java文件
为什么使用APT
- 方便简单,可以减少重复的代码
- ButterKnife之前通过运行时反射处理注解,实例化控价,增加点击事件等,造成性能下降,之后采用了APT生成代码,虽然新增了文件,但是降低了反射带来的性能损耗
一些使用APT的三方库
ButterKnife,ViewBinding,Dragger,EventBus等
如何使用APT
这里我们仿照ButterKnife,生成一个绑定view的类
1.自定义注解
新建一个Java Module,命名为bind-annotation
在主Module中添加依赖
implementation(project(":bind-annotation"))
新建注解类BindView
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.FIELD)
public @interface BindView {
int value();
}
@Retention表示注解的生命周期
RetentionPolicy | 生命周期 | 用法 | 举例 |
---|---|---|---|
SOURCE | 只保存在源文件中,当.java编译成.class,该注解被遗弃 | 一般用与运行期的检查 | @Override |
CLASS | 只保留到.class文件,当JVM加载,class文件时,该注解被遗弃 | 在编译时进行一些预处理操作 | @butterKnife |
RUNTIME | 在.class被装载时读取,程序运行期间一致保留 | 运行时动态获取注解信息 | @Deprecated |
@Target表示注解的范围,如FIELD表示成员变量,METHOD表示方法等
2.自定义注解处理器,并生成代码文件
新建一个java module,命名为 bind-processor,在主module中添加依赖
annotationProcessor(project(":bind-processor"))
添加依赖,这里通过 javapoet 来生成代码
dependencies {
implementation 'com.google.auto.service:auto-service:1.0-rc6'
implementation 'com.squareup:javapoet:1.10.0'
// Gradle 5.0后需要再加下面这行
annotationProcessor 'com.google.auto.service:auto-service:1.0-rc6'
implementation project(":bind-annotation")
}
新建注解处理器类BindViewProcessor和生成代码类ClassCreatorProxy
代码如下
@AutoService(Processor.class)
public class BindViewProcessor extends AbstractProcessor {
private Messager messager;
private Elements elements;
private Map<String, ClassCreatorProxy> proxyMap = new HashMap<>();
/**
* 初始化,可以得到很多实用的工具类
*
* @param processingEnv
*/
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
messager = processingEnv.getMessager();
elements = processingEnv.getElementUtils();
}
/**
* 指定这个注解处理器是注册给哪个注解的
*
* @return
*/
@Override
public Set<String> getSupportedAnnotationTypes() {
HashSet<String> set = new LinkedHashSet<>();
set.add(BindView.class.getCanonicalName());
return set;
}
/**
* 指定使用的Java版本
*
* @return
*/
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
/**
* 扫描、处理注解的代码,可以在此处生成Java文件
*
* @param annotations
* @param roundEnv
* @return
*/
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// 拿到所有的注解
Set<? extends Element> elementSets = roundEnv.getElementsAnnotatedWith(BindView.class);
for (Element element : elementSets) {
VariableElement variableElement = (VariableElement) element;
TypeElement classElement = (TypeElement) variableElement.getEnclosingElement();
String fullClassName = classElement.getQualifiedName().toString();
ClassCreatorProxy proxy = proxyMap.get(fullClassName);
if (proxy == null) {
proxy = new ClassCreatorProxy(elements, classElement);
proxyMap.put(fullClassName, proxy);
}
BindView annotation = variableElement.getAnnotation(BindView.class);
int value = annotation.value();
proxy.putElement(value, variableElement);
}
// 编译proxyMap,生成java文件
for (String key : proxyMap.keySet()) {
ClassCreatorProxy proxyInfo = proxyMap.get(key);
JavaFile javaFile = JavaFile.builder(proxyInfo.getPackageName(), proxyInfo.generateJavaCode2()).build();
try {
// 生成文件
javaFile.writeTo(processingEnv.getFiler());
} catch (IOException e) {
e.printStackTrace();
}
}
messager.printMessage(Diagnostic.Kind.NOTE, "process finish ...");
return true;
}
}
ClassCreatorProxy.java
public class ClassCreatorProxy {
private String mBindingClassName;
private String mPackageName;
private TypeElement mTypeElement;
private Map<Integer, VariableElement> mVariableElementMap = new HashMap<>();
public ClassCreatorProxy(Elements elementUtils, TypeElement classElement) {
this.mTypeElement = classElement;
PackageElement packageElement = elementUtils.getPackageOf(mTypeElement);
String packageName = packageElement.getQualifiedName().toString();
String className = mTypeElement.getSimpleName().toString();
this.mPackageName = packageName;
this.mBindingClassName = className + "_ViewBinding";
}
public void putElement(int id, VariableElement element) {
mVariableElementMap.put(id, element);
}
/**
* 加入Method
*
* @param builder
*/
private void generateMethods(StringBuilder builder) {
builder.append("public void bind(" + mTypeElement.getQualifiedName() + " host ) {\n");
for (int id : mVariableElementMap.keySet()) {
VariableElement element = mVariableElementMap.get(id);
String name = element.getSimpleName().toString();
String type = element.asType().toString();
builder.append("host." + name).append(" = ");
builder.append("(" + type + ")(((android.app.Activity)host).findViewById( " + id + "));\n");
}
builder.append(" }\n");
}
/**
* 创建Java代码
*
* @return
*/
public TypeSpec generateJavaCode2() {
TypeSpec bindingClass = TypeSpec.classBuilder(mBindingClassName)
.addModifiers(Modifier.PUBLIC)
.addMethod(generateMethods2())
.build();
return bindingClass;
}
/**
* 加入Method
*/
private MethodSpec generateMethods2() {
ClassName host = ClassName.bestGuess(mTypeElement.getQualifiedName().toString());
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("bind")
.addModifiers(Modifier.PUBLIC)
.returns(void.class)
.addParameter(host, "host");
for (int id : mVariableElementMap.keySet()) {
VariableElement element = mVariableElementMap.get(id);
String name = element.getSimpleName().toString();
String type = element.asType().toString();
methodBuilder.addCode("host." + name + " = " + "(" + type + ")(((android.app.Activity)host).findViewById( " + id + "));");
}
return methodBuilder.build();
}
public String getPackageName() {
return mPackageName;
}
}
3.在主界面调用
在MainActivity调用注解
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tvTest)
TextView tvTest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
build生成类
在app/build/generated/ap_generated_sources/debug/out/com/example/xxx/目录下即能看到生成的类
public class MainActivity_ViewBinding {
public void bind(MainActivity host) {
host.tvTest = (android.widget.TextView)(((android.app.Activity)host).findViewById( 2131231076));}
}
总结
APT动态性不足,通常只能用来创建新的类,而不能对原有的类进行改动。我们可以通过反射来弥补APT动态性的不足
参考
https://www.jianshu.com/p/7af58e8e3e18