joeking
joeking

Reputation: 2106

In gradle, what is the difference betweeen javaexec and a JavaExec task?

For example, I can have a JavaExec task:

task javaExecCaseA(type: JavaExec) {
    javaLauncher = javaToolchains.launcherFor {
        languageVersion = JavaLanguageVersion.of(11)
    }
    classpath = files("MySimpleProgram.jar")
}

or, inside a generic task:

task javaExecCaseB {
    doLast {
        javaexec {
            classpath = files("MySimpleProgram.jar")
        }
    }
}

I haven't figured out how to specify the JavaLanguageVersion in the 2nd case (javaExecCaseB). The bigger question though, is what is the difference?

I've tried various ways to set the version in javaExecCaseB, but I end up with an error like:

Could not set unknown property 'javaLauncher' for object of type org.gradle.process.internal.DefaultJavaExecAction_Decorated

Upvotes: 1

Views: 3903

Answers (1)

joeking
joeking

Reputation: 2106

I have found that the task is the gradle "JavaExec" task. And the 2nd case, javaexec is a Project method.

I began this quest to find a way to run Java programs using a different JVM than gradle itself is using (set from an environment variable or command line when running gradle).

I was able to get it to work in both cases:

ext {
    MyJvmVersion = 11
}

task SampleJavaExec1(type: JavaExec) {
    // Example task for using a custom JVM version with a JavaExec task
    javaLauncher = javaToolchains.launcherFor {
        languageVersion = JavaLanguageVersion.of(MyJvmVersion as int)
    }
    environment['JAVA_HOME'] = javaLauncher.get().metadata.installationPath.asFile.absolutePath
    classpath = files("MySimpleProgram.jar")
}

task SampleJavaExec2 {
    // Example task for using a custom JVM version with the javaexec method
    doLast {
        javaexec {
            environment['JAVA_HOME'] = "C:\\Program Files\\AdoptOpenJDK\\jdk-11.0.10.9-hotspot"
            executable = "C:\\Program Files\\AdoptOpenJDK\\jdk-11.0.10.9-hotspot\\bin\\java.exe"
            classpath = files("MySimpleProgram.jar")
        }
    }
}

In the 2nd case, javaexec() doesn't appear to have a "javaLauncher". Instead of hardcoding a path, I also found that I can use javaLauncher to find it for me by adding this code inside the javaexec{} block:

javaLauncher = javaToolchains.launcherFor {
    languageVersion = JavaLanguageVersion.of(MyJvmVersion as int)
}
environment['JAVA_HOME'] = javaLauncher.get().metadata.installationPath.asFile.absolutePath

This should invoke the auto download JVM resolution as well, but I've not tested that part.

Upvotes: 0

Related Questions