lexu lexu - 29 days ago 6
Groovy Question

Can't run a jar-file, built from groovy-code compiled with gradle

I'm trying to compile (with gradle) and execute (with the java 1.8 runtime) a small groovy program (see helloWorld.groovy, below).

But when I try to invoke it, I get Error: Could not find or load main class helloWorld

What am I missing?




compile:

lexu> gradle clean jar
:clean
:compileJava UP-TO-DATE
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar

BUILD SUCCESSFUL

Total time: 0.555 secs


execute:

lexu> java -jar ./build/libs/helloWorld.jar
Error: Could not find or load main class helloWorld


helloWorld.groovy:

class helloWorld {
static void main(String[] args) {
println('Hello World');
}
}


build.gradle:

apply plugin: 'groovy'
apply plugin: 'application'
mainClassName = "helloWorld"
archivesBaseName = 'helloWorld';
configurations {provided; inlib;}
repositories {mavenCentral()}
dependencies {compile 'org.codehaus.groovy:groovy-all:2.4.7'}
jar {
manifest {
attributes(
'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
'Main-Class': 'helloWorld'
)
}
}

Answer

There are a couple of issues with your setup.

  1. Not breaking, but worth mentioning here: Convention states your filenames and classes should be uppercase: HelloWorld.groovy

  2. gradle assumes your source files to be under src/main/java or in this case, src/main/groovy. You can configure it according to your preferences with gradle groovy plugin - project layout:


sourceSets {
    main {
        groovy {
            srcDirs = ['src/groovy']
        }
    }
}

  1. You need to include all runtime dependencies for groovy in your jar-archive. For this, let's use use an extended task called uberjar.

build.gradle:

apply plugin: 'groovy'
apply plugin: 'application'
mainClassName = "HelloWorld"
archivesBaseName = 'HelloWorld';
configurations {provided;  inlib;}
repositories {mavenCentral()}
dependencies {compile 'org.codehaus.groovy:groovy-all:2.4.7'}

task uberjar(type: Jar,dependsOn:[':compileJava',':compileGroovy']) {
    from files(sourceSets.main.output.classesDir)
    from configurations.runtime.asFileTree.files.collect { zipTree(it) }

    manifest {
        attributes 'Main-Class': mainClassName
    }
}

HelloWorld.groovy:

class HelloWorld {
   static void main(String[] args) {
      println('Hello World');
   }
}
Comments