Android Gradle插件2.2版本发布后,Android 官方提供了annotationProcessor来代替android-apt,annotationProcessor同时支持 javac 和 jack 编译方式,而android-apt只支持 javac 方式。同时android-apt作者宣布不在维护,当然目前android-apt仍然可以正常运行,如果你没有想支持 jack 编译方式的话,可以继续使用android-apt。
android-apt切换annotationProcessor步骤
1.Android Gradle 插件版本升级到 2.2 及以上
当前Android Studio已经升级到2.2版本
repositories {
jcenter()
}
dependencies {
classpath'com.android.tools.build:gradle:2.2.2'
classpath'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7'
classpath'com.github.dcendents:android-maven-gradle-plugin:1.5'
classpath'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:1.0.10'
}
}```
2.删除build.gradle文件中android-apt的相关配置
buildscript{repositories{ jcenter() }dependencies{classpath'com.neenbedankt.gradle.plugins:android-apt:1.8'} } apply plugin:'com.neenbedankt.android-apt'
3.改成新的依赖,build.gradle文件中使用android-apt引入的依赖修改为使用annotationProcessor,修改前配置如下:
dependencies{compile'com.google.dagger:dagger:2.0'apt'com.google.dagger:dagger-compiler:2.0'}
修改后配置如下:
dependencies{compile'com.google.dagger:dagger:2.0'annotationProcessor'com.google.dagger:dagger-compiler:2.0'}
配置完成后annotationProcessor的使用:
1.自定义注解
public @interface 注解名{注解体}。注解体中注解元素可以被public修饰,也可以什么也不写,元素类型可以是:
所有基本数据类型(int,float,boolean等)
String类型
Class类型
enum类型
Annotation类型(说明注解可以嵌套)
以上所有类型的数组
没有元素的标记注解
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.CLASS)
public@interfaceRequestCode{
}
单值注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface Uri {
String value();
}
2.使用注解:
@Uri("gank://androidwing.net/about/")
voidstartAbout();
3.自定义注解处理类库:
如果没有用来读取注解的工具,那注解也不会比注释更有用。使用注解的过程中很重要的一个部分就是创建与使用注解处理器:
public final class ServiceElement {
ClassName serviceClassName;
String packageName;
ClassName providerClassName;
List enclosedElements;
Element element;
public ServiceElement(Element serviceElement) {
element = serviceElement;
//获取类名
String className = serviceElement.getSimpleName().toString();
//获取包
PackageElement packageElement = (PackageElement) serviceElement.getEnclosingElement();
packageName = packageElement.getQualifiedName().toString();
serviceClassName = ClassName.get(packageName, className);
enclosedElements = serviceElement.getEnclosedElements();
String serviceProviderName = className +"$$Provider";
providerClassName = ClassName.get(packageName, serviceProviderName);
}
public String getPackageName() {
return packageName;
}
public ClassName getProviderClassName() {
return providerClassName;
}
public ClassName getClassName() {
return serviceClassName;
}
public List getEnclosedElements() {
return enclosedElements;
}
public Element getElement() {
return element;
}
}
该类用来储存注解类的信息,包括类,构造方法,成员变量,方法等
接下来就是注解生成类(注解处理器):
@Override
public booleanprocess(Set annotations, RoundEnvironment roundEnv) {
//数据处理
List addressElements = generateAddressElements(roundEnv);
//非空判断
if(ElementUtils.isEmpty(addressElements)) {
return false;
}
Map> serviceElements = findServiceElements(addressElements);
if(ElementUtils.isEmpty(serviceElements)) {
return false;
}
for(Map.Entry> serviceElementEntrySet : serviceElements.entrySet()) {
TypeElement serviceElement = serviceElementEntrySet.getKey();
ListserviceAddressElements= serviceElementEntrySet.getValue();
if(ElementUtils.isEmpty(serviceAddressElements)) {
break;
}
try{
//处理生成类
generateDeepLinkService(serviceElement,serviceAddressElements);
}catch(IOException e) {
logger.error("Error creating matcher file", serviceElement);
}
}
return true;
}
数据处理方法:
generateAddressElements(roundEnv)
privateList generateAddressElements(RoundEnvironment roundEnv) {
List annotationElements =newArrayList<>();
//注解类型数据处理
for(String annotationType : getSupportedAnnotationTypes()) {
TypeElement typeElement =processingEnv.getElementUtils().getTypeElement(annotationType);
Set annotatedElements = roundEnv.getElementsAnnotatedWith(typeElement);
for(Element annotatedElement : annotatedElements) {
if(!annotationElements.contains(annotatedElement)) {
annotationElements.add(annotatedElement);
}
}
}
List serviceElements =newArrayList<>();
for(Element element : annotationElements) {
ElementKind kind = element.getKind();
if(kind != ElementKind.METHOD) {
logger.error("Only classes and methods can be with "+ getSupportedAnnotationTypes(), element);
}
if(!isSupportReturnType((ExecutableElement) element)) {
logger.error("method only support return type is "+SUPPORT_RETURN_TYPE.toString(), element);
}
Element enclosingElement = element.getEnclosingElement();
String name = enclosingElement.getSimpleName().toString();
if(!name.endsWith("Service")) {
logger.error(name +"this class must be in end with Service", enclosingElement);
}
if(enclosingElement.getKind() != ElementKind.INTERFACE) {
logger.error(name +"this class must be interface", enclosingElement);
}
serviceElements.add(newAddressElement(element));
}
returnserviceElements;
}
数据处理好之后就是代码生成:
private voidgenerateDeepLinkService(TypeElement serviceElements,
List deepLinkMatchElements)
throwsIOException {
ClassName providerClassName = getServiceProviderClassName(serviceElements);
MethodSpec initMethod = generateInitMethod(deepLinkMatchElements);
//成员变量
FieldSpec activity = FieldSpec
.builder(DEEP_LINK_CLIENT,"deepLinkClient",
Modifier.PUBLIC)
.build();
//构造器定义
MethodSpec activityConstructor = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addParameter(DEEP_LINK_CLIENT,"deepLinkClient")
.addCode("this.deepLinkClient= deepLinkClient;\n")
.build();
//类定义
TypeSpec.Builder serviceProviderBuilder = TypeSpec.classBuilder(providerClassName)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(AnnotationSpec.builder(Aspect.class).build())
.addSuperinterface(ClassName.get(serviceElements))
.addField(activity)
.addMethod(activityConstructor)
.addMethod(initMethod);
//函数定义
for(AddressElement matchElement : deepLinkMatchElements) {
ExecutableElement element = (ExecutableElement) matchElement.getElement();
serviceProviderBuilder.addMethod(geneOverServiceMethod(element));
}
//构造注册
MethodSpec buildMethodSpec = generateBuildMethod(serviceElements);
serviceProviderBuilder.addMethod(buildMethodSpec);
//完成APT类的注解生成
JavaFile.builder(ClassName.get(serviceElements).packageName(), serviceProviderBuilder.build())
.build()
.writeTo(filer);
}
最后得到生成的类:
@Aspect
public final classSampleService$$ProviderimplementsSampleService {
publicDeepLinkClient deepLinkClient;
publicSampleService$$Provider(DeepLinkClient deepLinkClient) {
this.deepLinkClient = deepLinkClient;
}
public voidstartSecondActivity(String value1,intvalue2) {
Intent intent =newIntent();
intent.putExtra("key1", value1);
intent.putExtra("key2", value2);
intent.setData(Uri.parse("app://deeplink/second"));
Request request =this.deepLinkClient.buildRequest(intent);
if(request !=null) {
request.start();
}
}
}
总结:使用注解标签是非常方便一劳永逸,尤其是做些重复性且类似的处理,比如使用ButterKnife就不用重复写太多的控件find,虽然注解处理器处理起来比较麻烦,但想想接下来一大堆蛋疼的重复代码,所以还是值得一试。
本文借用了sunshine8大神的android组件化-路由器OkDeepLink代码。从中抽取了其中注解标签使用部分。
**参考文献:**
****
**[http://www.jianshu.com/p/8a3eeeaf01e8](http://www.jianshu.com/p/8a3eeeaf01e8)Android 组件化 —— 路由设计最佳实践**
[http://www.jianshu.com/p/c1666a947692](http://www.jianshu.com/p/c1666a947692)android-apt切换为官方annotationProcessor
网友评论