Gradle命令/配置来处理注释

时间:2015-09-16 17:14:35

标签: java gradle code-generation annotation-processing

我有一个Java项目,它使用注释处理器生成源代码,然后必须将其添加到编译类路径并进行编译/打包。

这个项目是由Gradle构建的,所以我想知道如何在引擎盖下调用这些注释处理器,以便:

  1. 首先处理注释,并在src/main/java下生成所需的源代码;然后
  2. 当Gradle进入编译阶段时,该源代码已经存在并且可以像所有其他源一样进行编译
  3. 当我运行gradle clean build时,代码不会生成,而其他源(依赖于生成的类在那里)会导致编译失败。

    我正在尝试了解需要做什么,以便Gradle运行必要的注释处理器并生成源代码。手头的特定处理器是Immutables所需的处理器。 project(也就是说,我的应用程序使用Immutables来生成不可变对象),但我认为这个问题的答案是一般的和项目无关的。

    更新

    像这样(?):

    dependencies {
        // ...
        apt 'com.squareup.dagger:dagger-compiler:1.1.0' 
        apt "org.immutables:value:2.0.21"
    
        compile 'com.squareup.dagger:dagger:1.1.0'         
    
        provided "org.immutables:value:2.0.21:annotations"
        provided "org.immutables:builder:2.0.21"
        provided "org.immutables:gson:2.0.21:annotations"
    }
    

1 个答案:

答案 0 :(得分:2)

这个应该可以帮到你:https://bitbucket.org/hvisser/android-apt。 以下链接示例:

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

修改

您想要使用的库似乎已经有手动http://immutables.github.io/getstarted.html

<强> EDIT2

compile指令为您的项目提供注释访问权限,但apt指令将启动apt(带注释的处理工具)。因此完整的build.gradle将是:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.7'
    }
}

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

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.yourpackage"//FIXME
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1//FIXME
        versionName "test"//FIXME
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    apt "org.immutables:value:2.0.21" // for annotation processor
    provided "org.immutables:value:2.0.21:annotations" // annotation-only artifact
    provided "org.immutables:builder:2.0.21" // there are only annotations anyway
    provided "org.immutables:gson:2.0.21:annotations" // annotation-only artifact
}
apt {
    arguments {
        resourcePackageName android.defaultConfig.applicationId
        androidManifestFile variant.outputs[0].processResources.manifestFile
    }
}