How do I use custom Java Annotation Processor in Gradle?

假如想象 提交于 2020-01-02 03:47:07

问题


I've been working on a simple java annotation processor that extends AbstractProcessor.

I've been able to successfully test this using javac -Processor MyProcessor mySource.java

The problem is integrating this into a simple Hello World android application using Android Studio.

I started by making a new Android Project, and then adding a separate module where I place all my annotation processor code (the MyProcessor class as well as the custom annotation it uses).

I then added this new module as a dependency of the HelloWorld android project.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':MyProcessorModule')
}

How do I then use the processor to generate code based on all the source files in the HelloWorld application?


回答1:


there's a plugin to make it work. It works perfectly with modules that are on Maven, not sure about local .jar files, but you sure give it a try:

here the plugin page: https://bitbucket.org/hvisser/android-apt

and here my build.gradle with it:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        ... add this classpath to your buildscript dependencies
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' << apply the plugin after the android plugin

dependencies {
    // in dependencies you call it
    apt 'com.company.myAnnotation:plugin:1.0-SNAPSHOT'
    compile 'com.company.myAnnotation:api:1.0-SNAPSHOT'

and it should work.




回答2:


Use the android-apt plugin. Better yet, fork a sample project that already uses the android-apt plugin for developing local annotation processors.

Read about the sample project here.




回答3:


what you are doing is perfectly right, here is an example of one of my projects that I use as a library:

dependencies {
    compile project(':boundservice')
}

of course what you should do also is to define the module you added your library as

android-library plagin and not application.

This should happen automatically if you do it using the New Module -> Android Library option, but maybe as this project, as I understand... has nothing to do with Android you should just chose the Java Library option.

When you do that and sync the build.gradle file (maybe a little clean build should help as well) you should be able to use your class files in the Android project.



来源:https://stackoverflow.com/questions/25649442/how-do-i-use-custom-java-annotation-processor-in-gradle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!