简体   繁体   中英

How to use a variable defined in build.gradle in .java file

I have a variable, say myVar, defined in build.gradle. I want to access this variable in some .java file which is a part of the same project. I know that we can do this in android using buildTypes block. But I have a non-android project in IntelliJ IDEA, so can't use it. I did come across a plugin https://github.com/mfuerstenau/gradle-buildconfig-plugin which lets me do that. But I don't want to rely on a 3rd party plugin. I also got to know about achieving this via setting the value to System properties and then accessing it in .java using System.getenv() . However, I don't want to change system-level stuffs. Any idea how to do this?

Store this variable value into some properties file (for example) that is copied by processResources , and load the properties file from the Java code, using the ClassLoader.

For example:

In src/main/resources/foo.properties , add the following line:

zimboom=${blabla}

In your build file, add the following configuration:

def myVar = 'hello';

processResources {
  fileMatching('foo.properties') {
    expand([blabla: myVar])
  }
}

In your Java source file, to get the value, use

Properties properties = new Properties();
properties.load(MyClass.class.getResourceAsStream("/foo.properties");
String zimboom = properties.getProperty("zimboom");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM