Search code examples
javaandroidgradleandroid-studioannotation-processing

How do I use custom Java Annotation Processor in Gradle?


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?


Solution

  • 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.