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

1

9

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?

Wahkuna answered 18/10, 2017 at 8:29 Comment(1)
Did you find a solution? I'm using a Java library module as well.Roumell
Y
2

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.

Yhvh answered 28/12, 2018 at 11:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.