Explain Codes LogoExplain Codes Logo

Gradle task - pass arguments to Java application

java
gradle
java-exec
application-plugin
Nikita BarsukovbyNikita Barsukov·Dec 15, 2024
TLDR

Pass arguments to your Java app more swiftly than a cheetah with Gradle. Setup a JavaExec task like so:

task runWithArgs(type: JavaExec) { mainClass = 'com.yourapp.Main' args 'firstArg', 'secondArg', 'thirdArg' }

Invoke with ./gradlew runWithArgs and voila! Your application now has arguments good to go!

Grappling with Gradle 4.9 and above

Gradle 4.9+ doesn't like to complicate things. Arguments are a breeze with the --args parameter. No fuss, just pass them as you run:

gradle run --args='arg1 arg2 arg3'

To enable this, ensure you've added the Application plugin and specified the main class entry point in your build.gradle, like this:

apply plugin: 'application' mainClassName = 'com.yourapp.Main'

And there you go, use run command to float your application on the sea of provided arguments.

Custom JavaExec tasks? No problem!

When you're going off the beaten track with custom JavaExec tasks, just pass arguments using the args method:

task customRun(type: JavaExec) { main = 'com.yourapp.CustomMainClass' // your own unique main class, because who likes copying anyway? args 'customArg1', 'customArg2' // random arguments, like "pineapple" on "pizza" }

Run this with ./gradlew customRun and your app is off to the races with 'customArg1' and 'customArg2'.

Keeping it cool with older Gradle versions (pre-4.9)

For the hipsters using pre-Gradle 4.9, you can still pass arguments. It's quirky, using project properties and if checks. Check this out:

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

Pass the arguments with:

gradle run -PappArgs="['arg1', 'arg2']"

Always one for the shelf!

When old Gradle needs a facelift

If you fancy the delights of --args but stuck with an older Gradle, consider sprucing up and upgrading Gradle. Get with the times!

Don't forget the Gradle version

Before going ham, take a breath to check your Gradle version. It could be your rookie mistake of the day! Use gradle --version and save yourself the agony of deprecated features.