如何使 GitHub 的不可变对象在 IntelliJ + Gradle 中工作

How to make GitHub's Immutables work in IntelliJ + Gradle

我使用 GitHub 的 Immutables 库进行 Android 开发,现在我也想在后端尝试一下。

在 Android 中,我需要做的就是使用这个库:

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

    // immutable entities generation
    provided "org.immutables:value:2.5.5" // for annotations
    provided "org.immutables:builder:2.5.5" // for annotations
    provided "org.immutables:gson:2.5.5" // for annotations

    ... other dependencies
}

当我尝试将上述依赖项复制到我的 Java 项目的 build.gradle 中时,出现此错误:

Error:(24, 0) Gradle DSL method not found: 'provided()'

我尝试用compileOnlycompile替换provided,但是没有生成用@Value.Immutable注释的接口的实现。

如何让它发挥作用?

找到答案了。分享以防对任何人(或将来我自己)有帮助。

首先,我必须按照 here 所述在 IntelliJ 中启用注释处理(尽管该选项现在位于 Settings > Build, Execution, Deployment > Compiler > Annotation Processors 中)。

之后,以下代码开始实际生成实现:

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

    // immutable entities generation
    compile "org.immutables:value:2.5.5" // for annotations
    compile "org.immutables:builder:2.5.5" // for annotations
    compile "org.immutables:gson:2.5.5" // for annotations

    ... other dependencies
}

但是,我仍然无法将实现自动导入到源文件中。

为了允许发现生成的 类,我不得不右键单击 main 包中的 generated 文件夹,然后 Mark Directory As > Generated Sources Root .

我无法添加评论(代表率太低),但对于未来的读者,我想扩展

在我的例子中(gradle 版本 5.2.1 中的包装器)以下代码自动神奇地发现生成的源:

dependencies {
    def immutablesVersion = "2.8.2"
    annotationProcessor "org.immutables:value:$immutablesVersion" // <--- this is important
    compileOnly "org.immutables:value:$immutablesVersion"
}

我不需要更改 IDE 注释处理器选项中的任何内容,它开箱即用。