Michał
Michał

Reputation: 636

How to pass command-line arguments to main class in gradle?

I am creating simple Java class and I would like to create out-of-the-box launcher by using gradle.

So I want to be able to run Java program via gradle:

gradlew clean run These are my command line arguments where These are my command line arguments are passed directly to my public static void main(String... args) method.

I am using the apply plugin: "application" which gives me the run task. But when I am running this 'as is' I've got:

* What went wrong: Task 'These' not found in root project 'question1'. Some candidates are: 'test'.

Upvotes: 9

Views: 12623

Answers (1)

Lukas Körfer
Lukas Körfer

Reputation: 14493

Gradle interprets each argument not starting with a hyphen (-) as task name to define which tasks will be executed during the build. Since a task with the name These does not exist, the build fails.

You are using the Gradle Application Plugin, which, as you already stated, provides a run task. The docs show, that the run task is of the type JavaExec. So, to apply your arguments, add them to the run task via args:

run {
    args 'These are my command line arguments'
}

To modify the arguments for each build without changing the build.gradle file, simply use project properties:

run {
    args findProperty('runArgs')
}

And call gradle clean run -PrunArgs='These are my command line arguments'

Upvotes: 12

Related Questions