Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 888
Hector Avatar asked Oct 18 '17 08:10

Hector


1 Answers

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.

like image 109
madhead - StandWithUkraine Avatar answered Dec 15 '22 23:12

madhead - StandWithUkraine