How to get gradle variables in my java method


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

1 Like

You can either

  1. Generate a resource at build time (eg a property file) which you add to your resources. You could then lookup the property file via the classloader at runtime
  2. Generate a java file at build time which you add to your java sources


task generateJava {
    ext.outputDir = "$buildDir/generated/java"'version', project.version)
    outputs.dir outputDir
    doLast {
        mkdir "$outputDir/com/foo"
        file("$outputDir/com/foo/").text = 
               |public class BuildProperties {
               |    public static String getVersion() { return "${project.version}"; }
compileJava.dependsOn generateJava 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

  1. Export the variables as Environment variables for Gradle Build and you should able to access them in Java Program too

  2. You have to customize Java Run task and share those properties explicitly with Java Program as arguments.