Java中使用Gradle中声明的变量
问题描述
是否可以在Gradle中声明一个可用于Java的变量?即在build.gradle中声明一些vars,然后在构建时得到这些变量。就像在C/C++中的pre-processor宏…
最佳解决方案
生成Java常量
android {
buildTypes {
debug {
buildConfigField "int", "FOO", "42"
buildConfigField "String", "FOO_STRING", "\"foo\""
buildConfigField "boolean", "LOG", "true"
}
release {
buildConfigField "int", "FOO", "52"
buildConfigField "String", "FOO_STRING", "\"bar\""
buildConfigField "boolean", "LOG", "false"
}
}
}
可以使用BuildConfig.FOO
访问
生成Android资源
android {
buildTypes {
debug {
resValue "string", "app_name", "My App Name Debug"
}
release {
resValue "string", "app_name", "My App Name Release"
}
}
}
可以使用@string/app_name
或R.string.app_name
以常规方式访问
次佳解决方案
Store api keys with help of gradle and the gradle.properties file (Java + XML)
- gradle.properties
AppKey="XXXX-XXXX"
- build.gradle
buildTypes {
//...
buildTypes.each {
it.buildConfigField 'String', 'APP_KEY_1', AppKey
it.resValue 'string', 'APP_KEY_2', AppKey
}
}
- Usage in java code
Log.d("UserActivity", "onCreate, APP_KEY: " + getString(R.string.APP_KEY_2));
BuildConfig.APP_KEY_1
- Usage in xml code
<data android:scheme="@string/APP_KEY_2" />
Link to an example of Api App Key usage in an Android application
Using String Constants Generated by Gradle Build Configurations
第三种解决方案
使用系统属性,在build.gradle中设置,从Java应用程序读取
在build.gradle中使用test任务,使用测试任务方法systemProperty设置在运行时传递的系统属性:
apply plugin: 'java'
group = 'example'
version = '0.0.1-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testCompile 'junit:junit:4.8.2'
compile 'ch.qos.logback:logback-classic:1.1.2'
}
test {
logger.info '==test=='
systemProperty 'MY-VAR1', 'VALUE-TEST'
}
Java中获取系统属性MY-VAR1,在runtime被设置为VALUE-TEST:
package example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
static final Logger log = LoggerFactory.getLogger(HelloWorld.class);
public static void main(String args[]) {
log.info("entering main...");
final String val = System.getProperty("MY-VAR1", "UNSET (MAIN)");
System.out.println("(main.out) hello, world: " + val);
log.info("main.log) MY-VAR1=" + val);
}
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/18/using-variables-declared-in-gradle-in-java/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
共有 0 条评论