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

Viewed 2382

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?

1 Answers

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");
Related