Gradle Java Application on Windows

Error: command line to long

Image by mohamed Hassan from Pixabay

If you create a Java application with the Gradle Application Plugin, you will sooner or later encounter the problem that the application can not be started under Windows.

The error message: command line too long

This limitation is documented in Windows Help.

But why does the error occur at all? (Needless to say, Microsoft just can not get it to develop a working OS?)

The problem can be found in Gradle’s Starter Script. It builds a CLASSPATH environment variable that contains the paths to all dependent JARs.

It will look like that:

set CLASSPATH=%APP_HOME%\lib\my-application-1.2.3.jar;%APP_HOME%\lib\jackson-module-kotlin-2.9.9.jar;%APP_HOME%\lib\kotlin-reflect-1.3.40.jar;%APP_HOME%\lib\kotlin-stdlib-jdk8-1.3.40.jar;%APP_HOME%\lib\slf4j-simple-1.7.25.jar;%APP_HOME%\.....

It’s clear that this variable gets bigger as the application gets more dependencies. The variable is then simply appended to the Java command as a -classpath parameter.

"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% -classpath "%CLASSPATH%" my.Application %CMD_LINE_ARGS%

Voila, you get a command line that will sooner or later exceed the limit.

But the problem is easy to work around. To do this you make use of the class-path property of the JAR Manifesto. Instead of directly appending the dependency list to the Java command, the list is simply appended to the JAR manifest of the application.

jar {
manifest {
attributes(
"Class-Path": (configurations.runtime.files)*.name.join(" ")
)
}
}
startScripts {
classpath = jar.outputs.files
}

From now on, the Starter Script will only have a classpath entry on the Application JAR.

set CLASSPATH=%APP_HOME%\lib\my-application-1.2.3.jar

All dependencies are now in MANIFEST.MF of my-application.jar

Manifest-Version: 1.0
Class-Path: jackson-module-kotlin-2.9.9.jar kotlin-reflect-1.3.40.jar kotlin-stdlib-jdk8-1.3.40.jar slf4j-simple-1.7.25.jar ...

Disclaimer: The solution was originally posted in the old Gradle Forum. However, I have adjusted it and completely abandon the “launcher” JAR.

Leave a Reply