--Command line arguments for Java applications run with gradle run can be specified with --args (available since Gradle 4.9 migration) --For example, you can set the parameter of the array of strings in the main method of Java main class by specifying gradle run --args = "aaa bbb ccc". --Before Gradle 4.9, it was dealt with by describing the pre-processing for executing the run task in build.gradle.
An example of specifying three arguments for aaa bbb ccc.
$ gradle run --args="aaa bbb ccc"
Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar, you can use gradle run --args="foo --bar" (see JavaExec.setArgsString(java.lang.String).
Confirmed to work with OpenJDK 11.0.2 and Gradle 5.6.2.
Prepare build.gradle and App.java for execution.
$ tree
.
├── build.gradle
└── src
└── main
└── java
└── com
└── example
└── App.java
build.gradle file.
build.gradle
plugins {
id 'java'
id 'application'
}
repositories {
mavenCentral()
jcenter()
}
application {
mainClassName = 'com.example.App'
}
App.java file.
package com.example;
public class App {
public static void main(String[] args) {
System.out.println("args.length=" + args.length);
for(String arg: args) {
System.out.println(arg);
}
}
}
Run gradle run with no arguments.
$ gradle run
> Task :run
args.length=0
BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 executed
Run gradle run with arguments.
$ gradle run --args="aaa bbb ccc"
> Task :run
args.length=3
aaa
bbb
ccc
BUILD SUCCESSFUL in 1s
2 actionable tasks: 1 executed, 1 up-to-date
Add the process when the run task is executed to build.gradle.
build.gradle
run {
//Pass the args property to args of the run task if it exists
if (project.hasProperty('args')) {
//Divide by half-width white space and pass
args(project.args.split('\\s+'))
}
}
If you specify the args property when running gradle run, it will be passed as an argument of the Java application.
$ gradle run -Pargs="aaa bbb ccc"
> Task :run
args.length=3
aaa
bbb
ccc
BUILD SUCCESSFUL in 1s
2 actionable tasks: 1 executed, 1 up-to-date
Recommended Posts