Search code examples
javagradlejarbuild.gradleuberjar

Gradle Uber (Fat) Jar and java.lang.NoClassDefFoundError in Runtime


I am trying to create a UberJar file with Gradle.

To build and run the jar file I execute commands ./gradlew clean build java -jar build/libs/jLocalCoin-0.2.jar

And I get Exception

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/primitives/Longs
    // ... rest of stacktrace
    at im.djm.zMain.Main03.main(Main03.java:13)
Caused by: java.lang.ClassNotFoundException: com.google.common.primitives.Longs
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 8 more

I don't understand what is the reason for the exception?
I do understand that Guava library is not part of the jar, but why?

In this questio, in the accepted answer, the jar file is created in the same way as I try to do.

This is build.grade file

apply plugin: 'java'
apply plugin: 'java-library'
apply plugin: 'application'

mainClassName = 'im.djm.zMain.Main03'

archivesBaseName = 'jLocalCoin'
version = "0.2"

run {
    standardInput = System.in
}

repositories {
    jcenter()
}

dependencies {
    implementation 'com.google.guava:guava:24.0-jre'

    testImplementation 'junit:junit:4.12'

    testCompile 'org.assertj:assertj-core:3.8.0'
}

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

Solution

  • The jar you created probably does not have guava in it. NoClassDefFoundError occurs when your project does not have required runtime dependecies in the classpath. The tutorial I checked created fatJar this way,

    task fatJar(type: Jar) {
       baseName = project.name + '-all'
       manifest {
            attributes 'Implementation-Title': 'Gradle Jar File Example',
                'Implementation-Version': version,
                'Main-Class': 'com.mkyong.DateUtils'
        }
       from { configurations.compile.collect { it.isDirectory() ? it : 
        zipTree(it) } 
        }
       with jar
    }
    

    and change implementation 'com.google.guava:guava:24.0-jre' to compile 'com.google.guava:guava:24.0-jre' then it does include guava in the generated jar

    and run command gradle fatJar

    source = https://www.mkyong.com/gradle/gradle-create-a-jar-file-with-dependencies/