Different ways to pass command line arguments to gradle command task


In this tutorial, You learned how to pass command line arguments from gradle build script.

gradle command line arguments passing 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

In this, Project properties are passed with -P option from 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 gradle command line

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

How to pass command line arguments using System environment properties

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

gradle -Dtest.hostname=localhost

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

Read the arguments using System.getProperty

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

This enables to pass all arguments and values

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

if you want to pass arguments to test cases from gradle script, First, read the properties and propagates to test 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, 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 command line, we can use below command

In windows, argumesn value 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’

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.