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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With