Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a main class in a jar from gradle using the 'java' command

I have these files under the <project_root> folder:

./build.gradle
./build/libs/vh-1.0-SNAPSHOT.jar
./libs/groovy-all-2.1.7.jar
./src/main/groovy/vh/Main.groovy

In the build.gradle file, I have this task:

task vh( type:Exec ) {
    commandLine 'java -cp libs/groovy-all-2.1.7.jar:build/libs/' +
            project.name + '-' + version + '.jar vh.Main'
}

The Main.groovy file is simple:

package vh

class Main {
    static void main( String[] args ) {
        println 'Hello, World!'
    }

}

After plugging in the string values, the command line is:

java -cp libs/groovy-all-2.1.7.jar:build/libs/vh-1.0-SNAPSHOT.jar vh.Main

If I run the command directly from shell, I get correct output. However, if I run gradle vh, it will fail. So, how do I make it work? Thank you very much.

like image 587
JBT Avatar asked Oct 01 '13 04:10

JBT


People also ask

How do I run a Gradle project from the command line?

To run a Gradle command, open a command window on the project folder and enter the Gradle command. Gradle commands look like this: On Windows: gradlew <task1> <task2> … ​ e.g. gradlew clean allTests.


1 Answers

Exec.commandLine expects a list of values: one value for the executable, and another value for each argument. To execute Java code, it's better to use the JavaExec task:

task vh(type: JavaExec) {
    main = "vh.Main"
    classpath = files("libs/groovy-all-2.1.7.jar", "build/libs/${project.name}-${version}.jar")
} 

Typically, you wouldn't have to hardcode the class path like that. For example, if you are using the groovy plugin, and groovy-all is already declared as a compile dependency (and knowing that the second Jar is created from the main sources), you would rather do:

classpath = sourceSets.main.runtimeClasspath

To find out more about the Exec and JavaExec task types, consult the Gradle Build Language Reference.

like image 199
Peter Niederwieser Avatar answered Oct 21 '22 02:10

Peter Niederwieser