3

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?

3
  • 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. Commented Jan 2, 2019 at 12:25
  • Could you point to some example? Or better if you could answer? Commented Jan 2, 2019 at 12:26
  • you could find similar question with some example solutions in the Gradle forum, here : discuss.gradle.org/t/… Commented Jan 2, 2019 at 12:30

1 Answer 1

5

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");
Sign up to request clarification or add additional context in comments.

2 Comments

Can I directly access myVar in .java file without introducing foo.properties?
gradle is a build tool. You use it to transform a bunch of source files into a runnable jar file. Once that is done, you run the jar file. That has nothing to do with gradle anymore. The jar file is supposed to be runnable on any machine, whether or not it has gradle installed. So, for a variable defined in a gradle build to be usable inside an application, the value of the variable somehow needs to be stored in the jar file of the application. Using a properties file is the easiest way to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.