美文网首页
Annotations 3

Annotations 3

作者: 比目鱼26 | 来源:发表于2017-02-25 16:03 被阅读0次

android-apt plugin

What is this?

android-apt插件可以看成是Android Studio下annotation processors的辅助工具.有2个作用:

  • annotation processor依赖仅仅作用于编译期,不包含在最后apk或者library中
  • annotation processor生成的.java文件设置source paths,这样确保在Android Studio中能被正确引用

Including and using the plugin in build script

配置project build.gradle

buildscript {
    repositories {
      mavenCentral()
    }
    dependencies {
        // replace with the current version of the Android plugin
        classpath 'com.android.tools.build:gradle:1.3.0'
        // the latest version of the android-apt plugin
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

Passing processor arguments

有些注解处理器需要传自定义参数,这就用到了apt.arguments.
比如AndroidAnnotation可以进行如下配置:

apt {
    arguments {
            resourcePackageName android.defaultConfig.applicationId
            androidManifestFile variant.outputs[0]?.processResources?.manifestFile
    }
}

AndroidAnnotations需要知道AndroidManifest.xml位置。通过检索variant为不同的flavor设置不同的AndroidManifest.xml。然而,并不是所有的variants(比如unit tests)有对应的属性,因此groovy的?.操作符确保安全性。

def getManifestByVariant(variant) {
    // return the value based on the variant
    if (variant.name == 'release') {
        return '/my/path/to/the/manifest.xml'
    }
    return variant.outputs[0]?.processResources?.manifestFile
}

apt {
     arguments {
         if (variant.name == 'debug') {
            resourcePackageName "com.myapp.package.name.debug"
            // more options
         }             
         androidManifestFile project.getManifestByVariant(variant)             
     }
}

Comfiguration a compiler style dependency

Annotations processors一般包含2个部分,分别是API和processor, processor生成的code被API所用(可以看作是包装wrap)。对于有些项目不同的依赖作用的时间范围是不一样的,比如Dagger有两个artifacts,分别是dagger-compiler和dagger,dagger-compiler仅仅作用于编译期,dagger作用于运行时。
配置这种依赖关系,插件增加apt configuration,如下:

dependencies {
 apt 'com.squareup.dagger:dagger-compiler:1.1.0'
 compile 'com.squareup.dagger:dagger:1.1.0'
}

对于instrumentation test code需要用到processor生成的code, 可用androidTestApt configuration:

dependencies {
 androidTestApt 'com.github.frankiesardo:android-auto-value-processor:0.1'
 androidTestCompile 'com.github.frankiesardo:android-auto-value:0.1'
}

Additional configuration

可以禁掉javac的默认发现机制,配置编译期指定的processor,具体操作如下:

apt {
    processor "my.class.name"
    processor "another.processor.class.name"
    // if you only want to run the processors above
    disableDiscovery true
}

Configuration of other annotation processor

如果processor和API用的是同一个artifact, 那么不需要特别配置,用compile 句柄添加即可。另外,如果processor生成的code在我们的项目中被引用了,android studio 能正确解决reference的问题。

annotationProcessor

Android Gradle plugin 2.2版本支持了apt插件的功能,不过有限制,那就是必须要开启jack,Hugo同时也提供了Migration方案,参考这篇文章

Sample

AptDemo

相关文章

网友评论

      本文标题:Annotations 3

      本文链接:https://www.haomeiwen.com/subject/mwtnwttx.html