APT:Annotation Processing Tools。编译期处理注解工具。
对源代码文件进行检测找出其中的Annotation,Annotation处理器在处理Annotation时可以根据源文件中的Annotation生成额外的源文件和其它的文件,APT还会编译生成的源文件和原来的源文件,将它们一起生成class文件。
简单的说:不影响性能的情况下,自动生成代码。
常用的ButterKnife、Dagger等都用注解生成代码的工具几乎都是用了APT。
四个元注解
@target: 目标位置,也就是注解可以被用在那里,如方法、属性、类
@Retention:保留级别,也就是注解生效的时间,换言之理解为"生命周期"
@Documented:包含进文档
@Inherited:子类继承父类注解
APT工作流程
- 定义注解
- 定义注解处理器 (AbstractProcess)
- 处理器中生成java代码 (javaPoet)
- 注册处理器 (AutoService)
注册处理器的大致流程(使用AutoService可以直接解决注册)
- 继承AbstractProcessor,process()方法处理主要逻辑。
- 处理器由相应工厂AnnotationProcessFactory工厂返回
- 两种获得工厂的方法。命令行直接运行已知工厂;jar指定路径检索。
例子
简单实现类似ButterKnife自动生成findviewById功能。
1.创建Java lib,存放所有的注解文件
BindView代码如下,没什么具体的东西,毕竟这里只需要传入一个View id。
package com.example.fengz.apt_annotation.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.CLASS)
public @interface BindView {
int value();
}
2.创建java lib,注册处理器,生成代码逻辑处理
这里用AutoService注册,javapoet快速生成代码
build.gradle内容如下:
apply plugin: 'java-library'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.auto.service:auto-service:1.0-rc2'
implementation project(':apt-annotation')
implementation 'com.squareup:javapoet:1.10.0'
}
sourceCompatibility = "1.7"
targetCompatibility = "1.7"
文档结构如下:
BindViewProcessor处理注册逻辑
package com.example.fengz.apt_processor.processor;
import com.example.fengz.apt_annotation.annotation.BindView;
import com.example.fengz.apt_processor.AClassCreatorProxy;
import com.example.fengz.apt_processor.ClassCreatorProxy;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Processor;
import javax.lang.model.element.Element;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
@AutoService(Processor.class)
public class BindViewProcessor extends AbstractProcessor {
private Elements mElementUtils;
private Map<String, AClassCreatorProxy> mProxyMap = new HashMap<>();
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
mElementUtils = processingEnv.getElementUtils();
}
/**
* 指定这个注解处理器是注册给哪个注解的,这里说明是注解BindView
*/
@Override
public Set<String> getSupportedAnnotationTypes() {
HashSet<String> supportTypes = new LinkedHashSet<>();
supportTypes.add(BindView.class.getCanonicalName());
return supportTypes;
}
/**
* 指定使用的Java版本,通常这里返回SourceVersion.latestSupported()
*/
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
//根据注解生成Java文件
mProxyMap.clear();
//得到所有的注解
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(BindView.class);
for (Element element : elements) {
VariableElement variableElement = (VariableElement) element;
TypeElement classElement = (TypeElement) variableElement.getEnclosingElement();
String fullClassName = classElement.getQualifiedName().toString();
AClassCreatorProxy proxy = mProxyMap.get(fullClassName);
if (proxy == null) {
proxy = new AClassCreatorProxy(mElementUtils, classElement);
mProxyMap.put(fullClassName, proxy);
}
BindView bindAnnotation = variableElement.getAnnotation(BindView.class);
int id = bindAnnotation.value();
proxy.putElement(id, variableElement);
}
//通过遍历mProxyMap,创建java文件
// for (String key : mProxyMap.keySet()) {
// ClassCreatorProxy proxyInfo = mProxyMap.get(key);
// try {
// JavaFileObject jfo = processingEnv.getFiler().createSourceFile(proxyInfo.getProxyClassFullName(), proxyInfo.getTypeElement());
// Writer writer = jfo.openWriter();
// writer.write(proxyInfo.generateJavaCode());
// writer.flush();
// writer.close();
// } catch (IOException e) {
// }
// }
for (String key : mProxyMap.keySet()) {
AClassCreatorProxy proxyInfo = mProxyMap.get(key);
JavaFile javaFile = JavaFile.builder(proxyInfo.getPackageName(), proxyInfo.generateJavaCode2()).build();
try {
// 生成文件
javaFile.writeTo(processingEnv.getFiler());
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
}
AClassCreatorProxy:处理生成代码逻辑
package com.example.fengz.apt_processor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import java.util.HashMap;
import java.util.Map;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
/**
* JavaPoet生成java代码
*/
public class AClassCreatorProxy {
private String mBindingClassName;
private String mPackageName;
private TypeElement mTypeElement;
private Map<Integer, VariableElement> mVariableElementMap = new HashMap<>();
public AClassCreatorProxy(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);
}
/**
* 创建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.创建Android lib, 调用生成文件
文档结构如下:
BindViewTools功能类似ButterKnife.bind();
package com.example.fengz.apt_library.lib;
import android.app.Activity;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BindViewTools {
public static void bind(Activity activity) {
Class clazz = activity.getClass();
try {
Class bindViewClass = Class.forName(clazz.getName() + "_ViewBinding");
Method method = bindViewClass.getMethod("bind", activity.getClass());
method.invoke(bindViewClass.newInstance(), activity);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
4.检测工具是否可用,创建app module
package com.example.fengz.aptdemoj;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import com.example.fengz.apt_annotation.annotation.BindView;
import com.example.fengz.apt_library.lib.BindViewTools;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv)
TextView mTextView;
@BindView(R.id.btn)
Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BindViewTools.bind(this);
mTextView.setText("bind TextView success");
mButton.setText("bind Button success");
}
}
运行,工具OK!
在build路劲找到自动生成的代码:
代码如下:
package com.example.fengz.aptdemoj;
public class MainActivity_ViewBinding {
public void bind(MainActivity host) {
host.mButton = (android.widget.Button) (((android.app.Activity) host).findViewById(2131165218));
host.mTextView = (android.widget.TextView) (((android.app.Activity) host).findViewById(2131165326));
}
}