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.JB Nizet– JB Nizet2019-01-02 12:25:08 +00:00Commented Jan 2, 2019 at 12:25
-
Could you point to some example? Or better if you could answer?Ankit Shubham– Ankit Shubham2019-01-02 12:26:28 +00:00Commented Jan 2, 2019 at 12:26
-
you could find similar question with some example solutions in the Gradle forum, here : discuss.gradle.org/t/…M.Ricciuti– M.Ricciuti2019-01-02 12:30:11 +00:00Commented Jan 2, 2019 at 12:30
Add a comment
|
1 Answer
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");
2 Comments
Ankit Shubham
Can I directly access myVar in .java file without introducing foo.properties?
JB Nizet
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.