Search code examples
androidandroid-studiokotlinjava-annotationskapt

Annotation processing with kapt Android Studio


I'm trying to use kapt for using my annotation processor. But I ran into a few problems.

Annotation processor jar is connected this way:

    kapt files('libs/processor.jar')
    provided files('libs/processor.jar')

1) I'm using JavaPoet for code generation. And saving my class this way

    JavaFile javaFile = JavaFile.builder(PACKAGE, typeSpec).build();
    javaFile.writeTo(processingEnv.getFiler());

But it always saves it to build\generated\source\kapt\release, and never to debug folder regardless of build variant.

enter image description here

2) The second problem is that generated file sometimes doesn't refresh, until I press Build->Rebuild


Solution

  • The kotlin-kapt plugin will automatically select the correct output directory based on the built library/application variant. When building a project with a single com.android.application module, Android Studio will use the application variant selected in the "Build Variants" menu.

    Build variants window

    This is not true for library modules, which, if not configured otherwise, will publish the release build variant – even when you select "debug" for those modules inside the "Build Variants" menu.

    To get kapt up and running for library modules, you have three options:

    1. In the "Build Variants" window, select "release" for the library module containing your annotated code. This will tell Android Studio to pick up the kapt output inside generated/sources/kapt/release/.

    2. In your library modules build.gradle set the defaultPublishConfig to debug (and keep the selected variant at debug too). This will tell the Android Gradle plugin to compile the debug library variant instead of the default release one.

      android {
          defaultPublishConfig "debug"
      }
      
    3. You can also choose to publish both the debug and release build variants ant the same time, by setting publishNonDefaults to true. In your main app module, you can then reference the library module twice, for debugCompile and releaseCompile configurations. However, note that this will always build both types, even though you might only require debug sources at the time of building, practically doubling compile times.