如何在Gradle Java库项目构建脚本中指定buildConfigField
在我的Android项目中,我可以指定Gradle常量,如下所示:
Within my Android projects I can specify Gradle constants as follows:
buildConfigField 'Boolean', 'analyticsEnabled', 'false'
并在我的Android应用程序中访问它们,如下所示:-
and access them in my Android application like this:-
public boolean isAnalyticsEnabled() {
return BuildConfig.analyticsEnabled;
}
如何在Java库Gradle构建脚本中获得相同的功能?
How can I get the same functionality within a Java library Gradle build script?
更准确地说,我正在将自定义注释处理器开发为我的Android应用程序所依赖的纯Java项目(库).
To be more precise, I am developing a custom annotation processor as a pure Java project (library) that my Android application is dependant on.
我想在Java Gradle构建文件中定义可由注释处理器访问的常量.
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?
您可以使用这些插件.例如. de.fuerstenau.buildconfig
:
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'
}
然后获得一个BuildConfig
类,例如:
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;
}
如果您正在使用Kotlin并想生成Kotlin版本BuildConfig
,请查看 io.pixeloutlaw.gradle.buildconfigkt
.
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
(这些值与project.question
和project.answer
相同):
question=Life, The Universe, and Everything
answer=42
src/main/resources/buildconfig.properties
:
question=${question}
answer=${answer}
然后只需在应用程序中将buildconfig.properties
读入Properties
并使用这些值即可.
Then just read buildconfig.properties
into Properties
in your app and use the values.