RecuencoJones
RecuencoJones

Reputation: 2867

Gradle task - pass arguments to Java application

I have a Java application that runs with a custom gradle task and the application requires some arguments upon being invoked. These are:

programName ( string | -f filename | -d key | -h)
Options:
    string         Message to be used.
    -d key         Use default messages, key must be s[hort], m[edium] or l[ong].
    -f filename    Use specified file as input.
    -h             Help dialog.

Gradle task looks like:

task run (type: JavaExec){
    description = "Secure algorythm testing"
    main = 'main.Test'
    classpath = sourceSets.main.runtimeClasspath
}

I've tried running gradle run -h and it does not work.

Upvotes: 164

Views: 154058

Answers (10)

RecuencoJones
RecuencoJones

Reputation: 2867

I figured an answer similar to @xlm 's:

task run (type: JavaExec, dependsOn: classes){
    if(project.hasProperty('myargs')){
        args(myargs.split(','))
    }
    description = "Secure algorithm testing"
    main = "main.Test"
    classpath = sourceSets.main.runtimeClasspath
}

Usage e.g.:

gradle run -Pmyargs=-d,s

Upvotes: 28

djhallx
djhallx

Reputation: 739

Here is what I found when I was trying to pass Spring Boot JPA parameters into an application that I was launching from the command line. (I'm using Gradle 7.6.1)

First, in your build.gradle file:

if (project.hasProperty("args")) {
    ext.cmdargs = project.getProperty("args")
} else { 
    ext.cmdargs = ""
}

Then, also in your build.gradle file:

task runDemo(dependsOn: 'jar') {
    doLast {
        javaexec {
            classpath = sourceSets.main.runtimeClasspath
            jvmArgs = [ "-Xmx8G" ]
            mainClass = "my.demo.app.App"
            args cmdargs.split()
        }

    }
}

Then, to run "runDemo" on a bash command line, you do the following:

$ ./gradlew runDemo -Pargs='arg1 -arg2 --arg3 
--spring.datasource.username=myusername
--spring.datasource.password=mypassword
--spring.datasource.driver-class-name=some.sql.Driver'

Some notes:

  1. -P creates a property, args in this case, that is passed to gradle.
  2. The args property value is enclosed in single quotes.
  3. Because I'm using bash and my args property value spanned multiple lines, I didn't have to do anything special because of how bash interprets text contained within single quotes. Specifically, you do not need a backslash on the end of each line to continue on the next line within the text bounded by single quotes.
  4. The build.gradle file reads the args property and puts the value in ext.cmdargs. Then, the runDemo task calls cmdargs.split() and puts the resulting array into the args variable that is passed into you application.

Upvotes: 0

devatherock
devatherock

Reputation: 4921

Building on Eng.Fouad's answer, with Kotlin DSL and application plugin, use something like below, to pass arguments to only the run task added by the application plugin, instead of to all the tasks of type JavaExec:

plugins {
    application
}

application {
    mainClass.set("main.Test")
}

tasks.run<JavaExec> {
    args(listOf("-h"))
}

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117589

Using Kotlin DSL:

plugins {
    java
    application
}

application {
    mainClass = "io.fouad.AppLauncher"
    applicationDefaultJvmArgs = listOf("-Dsome.system.properties=123")
}

tasks.withType(JavaExec::class) {
    args = listOf("abc", "def")
}

Upvotes: 0

xlm
xlm

Reputation: 7594

Gradle 4.9+

gradle run --args='arg1 arg2'

This assumes your build.gradle is configured with the Application plugin. Your build.gradle should look similar to this:

plugins {
  // Implicitly applies Java plugin
  id: 'application'
}

application {
  // URI of your main class/application's entry point (required)
  mainClassName = 'org.gradle.sample.Main'
}

Pre-Gradle 4.9

Include the following in your build.gradle:

run {
    if (project.hasProperty("appArgs")) {
        args Eval.me(appArgs)
    }
}

Then to run: gradle run -PappArgs="['arg1', 'args2']"

Upvotes: 139

AMing
AMing

Reputation: 5747

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 Also Gradle Application Plugin

How to upgrade Gradle wrapper

Upvotes: 112

Boaz Nahum
Boaz Nahum

Reputation: 1097

Of course the answers above all do the job, but still i would like to use something like

gradle run path1 path2

well this can't be done, but what if we can:

gralde run --- path1 path2

If you think it is more elegant, then you can do it, the trick is to process the command line and modify it before gradle does, this can be done by using init scripts

The init script below:

  1. Process the command line and remove --- and all other arguments following '---'
  2. Add property 'appArgs' to gradle.ext

So in your run task (or JavaExec, Exec) you can:

if (project.gradle.hasProperty("appArgs")) {
                List<String> appArgs = project.gradle.appArgs;

                args appArgs

 }

The init script is:

import org.gradle.api.invocation.Gradle

Gradle aGradle = gradle

StartParameter startParameter = aGradle.startParameter

List tasks = startParameter.getTaskRequests();

List<String> appArgs = new ArrayList<>()

tasks.forEach {
   List<String> args = it.getArgs();


   Iterator<String> argsI = args.iterator();

   while (argsI.hasNext()) {

      String arg = argsI.next();

      // remove '---' and all that follow
      if (arg == "---") {
         argsI.remove();

         while (argsI.hasNext()) {

            arg = argsI.next();

            // and add it to appArgs
            appArgs.add(arg);

            argsI.remove();

        }
    }
}

}


   aGradle.ext.appArgs = appArgs

Limitations:

  1. I was forced to use '---' and not '--'
  2. You have to add some global init script

If you don't like global init script, you can specify it in command line

gradle -I init.gradle run --- f:/temp/x.xml

Or better add an alias to your shell:

gradleapp run --- f:/temp/x.xml

Upvotes: 6

Claudio Fahey
Claudio Fahey

Reputation: 800

If you want to use the same set of arguments all the time, the following is all you need.

run {
    args = ["--myarg1", "--myarg2"]
}

Upvotes: 41

You can find the solution in Problems passing system properties and parameters when running Java class via Gradle . Both involve the use of the args property

Also you should read the difference between passing with -D or with -P that is explained in the Gradle documentation

Upvotes: 7

cjstehno
cjstehno

Reputation: 13984

You need to pass them as args to the task using project properties, something like:

args = [project.property('h')]

added to your task definition (see the dsl docs)

Then you can run it as:

gradle -Ph run

Upvotes: 4

Related Questions