如何使GitHub的Immutables在IntelliJ + Gradle中工作

Vas*_*liy 10 java intellij-idea gradle build.gradle immutables-library

我使用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
}
Run Code Online (Sandbox Code Playgroud)

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

Error:(24, 0) Gradle DSL method not found: 'provided()'
Run Code Online (Sandbox Code Playgroud)

我试图providedcompileOnly和替换compile,但是然后@Value.Immutable没有生成带注释的接口的实现.

我如何使其工作?

Vas*_*liy 8

找到了答案.分享以防任何人(或将来我自己)都会有所帮助.

首先,我不得不启用的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
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 对于较新版本的 Gradle,值得关注 /sf/answers/4194241621/ (2认同)

nou*_*veu 6

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

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

dependencies {
    def immutablesVersion = "2.8.2"
    annotationProcessor "org.immutables:value:$immutablesVersion" // <--- this is important
    compileOnly "org.immutables:value:$immutablesVersion"
}
Run Code Online (Sandbox Code Playgroud)

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

  • 由于这是对现有答案的扩展,提供了回答问题的附加信息,因此将其作为答案发布是完全合法的。即使您有评论权限,答案仍然是合理的。就像一般提示一样,如果您直接引用另一个答案,您可以像我一样通过编辑您的帖子来链接到它。我知道如果只有一个其他答案,这可能看起来并不重要,但将来可以有更多答案,所以很高兴有:) (3认同)