JavaExec - How to execute a main class from the command line with Gradle

Steps

The build file

The below build file define a JavaExec task with the name myCli and set:

  • the main class
  • the class path
  • the current directory
  • the arguments
val cd: String by project
val arguments: String by project

tasks.register<JavaExec>("myCli") {
  main = "com.example.cli"
  classpath = sourceSets["main"].runtimeClasspath
  if(project.hasProperty("cd")){
    workingDir = File(cd)
  }
  if (project.hasProperty("arguments")){
    /**
     * We split and escape the arguments to not have any file wildcard expansion
     * (ie star will not become a list of files)
     */
    args = arguments.split(" ").map{s->"\""+s+"\""}
  }
}

The dos script

The dos script that calls the task myCli. This file should located at the root of the gradle project (otherwise you need to change the --project-dir option.

@ECHO OFF
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

SET SCRIPT_PATH=%~dp0

REM This script call the myCli task defined in the gradle.kts build
REM The properties are passed via argument


@if ".%*" == "." (
	@gradle myCli --project-dir %SCRIPT_PATH% -PcurrentDirectory=%cd%
) ELSE (
	@gradle myCli --project-dir %SCRIPT_PATH% -PcurrentDirectory=%cd% -Parguments="%*"
)

if "%OS%"=="Windows_NT" endlocal





Discover More
Gradle - Project Property

Project property is a type property that has a project scope You can access a project property in your build script simply by using its name as you would use a variable. Example: project property...



Share this page:
Follow us:
Task Runner