简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM