Different ways to pass command line arguments to Gradle command task

You learned how to pass command-line arguments from the Gradle build script.

In Gradle, We can pass parameters below types of parameters.

  • Project properties using -P option
  • java system properties using -D option
  • args option with application plugin

How to pass project command-line properties with Gradle script

Project properties pass with the -P option from the Gradle command.

In build.gradle, task run has configured to read arguments with project.hasProperty

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

And java class to read arguments

public class Test {
public static void main(String[] args) throws Exception {
           for (String item : args) {
            System.out.println("[" + item + "]");
        }
}

Let’s see how we can pass arguments from the Gradle command line

gradle run  -Pargsarray="['one','two']"

How to pass command-line arguments using System environment properties

Like the java command line, the Gradle command also accepts parameters with the -D option Here is a command to pass custom properties to the command line.

gradle -Dtest.hostname=localhost

In build.gradle, you can configure it in the ext block. ext block holds all user-defined properties related to project, system, and task arguments.

Read the arguments using System.getProperty

ext {
   hostname = System.getProperty("test.hostname", "localhost");
}

It enables the passing of all arguments and values.

you can read the value using the project.ext.hostname property anywhere in the Gradle script

if you want to pass arguments to test cases from the Gradle script, First, read the properties and propagates to test the task.

test {
       systemProperty "test.hostname", "localhost"
}

below pass all system properties to Gradle test tasks

test {
               systemProperties(System.getProperties())

using application plugin with —args option

First, configure the application, and java plugin in build.gradle.

apply plugin: "java"
apply plugin: "application"

application {
    mainClassName = com.ch.Test
}

Here is a java class

package com.ch;
public class Test {
    public static void main(String[] args) {
        System.out.println(args);
    }
}

From the command line, we can use the below command.

In windows, the argument value is enclosed in double-quotes.

gradlew run --args="welcome to java class"

In Linux, We can use single quotes gradlew run —args=‘welcome to java class’