使用kapt在Android Studio中进行注解处理

4
我正在尝试使用kapt来使用我的注解处理器,但是遇到了一些问题。
注解处理器jar包是这样连接的:
    kapt files('libs/processor.jar')
    provided files('libs/processor.jar')

1) 我正在使用 JavaPoet 进行代码生成。并以这种方式保存我的类

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

但是它总是保存到build\generated\source\kapt\release文件夹下,而不管构建的变体是debug还是其他。

enter image description here

2) 第二个问题是生成的文件有时候不会自动刷新,除非我按下“构建-重建”按钮。


你找到解决办法了吗?我也遇到了同样的问题。 - david.schreiber
@david.schreiber,文件夹的问题已经通过仅在应用程序模块中使用处理器来“解决”。但是文件更新的问题仍然存在。您是否正在使用Kotlin 1.0.6?也许他们在kapt中修复了这些问题? - Ufkoku
我也遇到了库模块的问题,但在分析gradle输出后,我注意到只有发布版本的源代码被构建。原因是,默认情况下,库模块只会发布发布版本的构件:http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication 我已经添加了我的答案到这个问题。 - david.schreiber
1个回答

2
“kotlin-kapt”插件将根据构建的库/应用程序变体自动选择正确的输出目录。在使用单个“com.android.application”模块构建项目时,Android Studio将使用“Build Variants”菜单中选定的应用程序变体。

Build variants window

这对于库模块来说不是真的,如果没有进行其他配置,默认情况下,它们将发布release构建变体——即使你在“Build Variants”菜单中选择了这些模块的“debug”选项。

为了让库模块运行起来,你有三个选项:

  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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接