How do you specify buildConfigField in Gradle Java-library Project build script

你离开我真会死。 提交于 2020-01-13 09:45:46

问题


Within my Android projects I can specify Gradle constants as follows:

buildConfigField 'Boolean', 'analyticsEnabled', 'false'

and access them in my Android application like this:-

public boolean isAnalyticsEnabled() {
        return BuildConfig.analyticsEnabled;
}

How can I get the same functionality within a Java library Gradle build script?

To be more precise, I am developing a custom annotation processor as a pure Java project (library) that my Android application is dependant on.

I would like to define constants within my Java Gradle build file that are accessible by my annotation processor.

If this is possible, then how to I achieve it?


回答1:


You can use one of these plugins. E.g. de.fuerstenau.buildconfig:

build.gradle:

plugins {
    id 'de.fuerstenau.buildconfig' version '1.1.8'
}

buildConfig {
    buildConfigField 'String', 'QUESTION', '"Life, The Universe, and Everything"'
    buildConfigField 'int', 'ANSWER', '42'
}

And then get a BuildConfig class like:

public final class BuildConfig
{
    private BuildConfig () { /*. no instance */ }

    public static final String VERSION = "unspecified";
    public static final String NAME = "DemoProject";

    public static final String QUESTION = "Life, The Universe, and Everything";
    public static final int ANSWER = 42;
}

If you're using Kotlin and want to generate a Kotlin version BuildConfig take a look at io.pixeloutlaw.gradle.buildconfigkt as well.

If don't like that idea, what you can do is resource filtering:

build.gradle:

processResources {
    expand project.properties
}

gradle.properties (these values are the same as project.question and project.answer):

question=Life, The Universe, and Everything
answer=42

src/main/resources/buildconfig.properties:

question=${question}
answer=${answer}

Then just read buildconfig.properties into Properties in your app and use the values.



来源:https://stackoverflow.com/questions/46805846/how-do-you-specify-buildconfigfield-in-gradle-java-library-project-build-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!