Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a task to call a main class

Tags:

gradle

groovy

What I am trying to do is make a task in build.gradle that will execute a main class (class with the main method), but I don't know how.

I made a test project to test how to do that. Here is the file structure layout:

testProject/
    build.gradle
    src/main/groovy/hello/world/HelloWorld.groovy

Here is the content of build.gradle:

apply plugin: 'groovy'
apply plugin: 'maven'

repositories {
    mavenCentral()
}

dependencies {
    compile     'org.codehaus.groovy:groovy-all:2.0.6'
}

task( hello, dependsOn: jar, type: JavaExec ) {
    main = 'hello.world.HelloWorld'
}

Here is the content of HelloWorld.groovy:

package hello.world

class HelloWorld {
    public static void main(String[] args) {
        println "Hello World!"
    }
}

Here is what I get from shell:

testProject>$ gradle hello
:compileJava UP-TO-DATE
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar UP-TO-DATE
:hello
Error: Could not find or load main class hello.world.HelloWorld
:hello FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':hello'.
> Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 4.232 secs

So, my question is: how can I make gradle hello work? Thank you very much.

like image 793
JBT Avatar asked Aug 12 '13 19:08

JBT


People also ask

What is JavaExec?

JavaExec. Executes a Java application in a child process. Similar to Exec , but starts a JVM with the given classpath and application class.

How do I run a program in gradle?

You can run the application by executing the run task (type: JavaExec). This will compile the main source set, and launch a new JVM with its classes (along with all runtime dependencies) as the classpath and using the specified main class.


1 Answers

After a bit of googling, I found a solution. The only thing I need to change is the task block. The working one is pasted below:

task( hello, dependsOn: jar, type: JavaExec ) {
    main = 'hello.world.HelloWorld'
    classpath = sourceSets.main.runtimeClasspath
}
like image 106
JBT Avatar answered Nov 11 '22 17:11

JBT