Hi,
I created a variable as "version ‘1.0’ in build.gradle. But I am trying to get that variable value in my java method. Please suggest me how to get those variables
Hi,
I created a variable as "version ‘1.0’ in build.gradle. But I am trying to get that variable value in my java method. Please suggest me how to get those variables
You can either
Eg:
task generateJava {
ext.outputDir = "$buildDir/generated/java"
inputs.property('version', project.version)
outputs.dir outputDir
doLast {
mkdir "$outputDir/com/foo"
file("$outputDir/com/foo/BuildProperties.java").text =
"""|package com.foo
|public class BuildProperties {
| public static String getVersion() { return "${project.version}"; }
|}""".stripMargin()
}
}
compileJava.dependsOn generateJava
sourceSets.main.java.srcDir generateJava.outputDir
Hi Lance,
Thanks for the reply. Looks like it generates a Java file in the build directory.
Is there any way to call directly Gradle variables in my java function without generating a java file
I’m hoping you realise that Gradle is a build time concept which ultimately compiles java files into classes and packs them into a jar/war/zip.
At runtime, you don’t have Gradle and you can’t look at your source files either. You must rely on what’s packed into your jar/war/zip.
As I originally said, another option is to generate a resource file (eg a property file) at build time which is added to your jar. At runtime you could look up the property file via the classpath/classloader.
Your question is big vague… Gradle is build tool, but not application runtime.
If you are trying to execute a Java Programs in Gradle Build and wants to access gradle variables
Export the variables as Environment variables for Gradle Build and you should able to access them in Java Program too
You have to customize Java Run task and share those properties explicitly with Java Program as arguments.