Search code examples
javagradleguava

NoClassDefFoundError when using Guava classes even though Guava is included in Gradle build file and on classpath


When I build my Guava dependent project with Gradle using:

//build.gradle

plugins {
    id 'java'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'com.google.guava', name: 'guava', version: '22.0'
}

task wrapper(type: Wrapper) {
    gradleVersion = '3.3' //Tried 3.1 - 4.0.1 
    distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip"
}

I get the following runtime error when running the project in Intellij:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/Multiset

The libraries are definitely in the classpath and I cannot figure out why this is happening.

I have solved this problem by switching to an older Gradle version (3.1, 3.2, 3.3 all work).

Therefore, I believe the problem lies with Gradle 3.4+ (3.4, 3.5.1, 4.0 and 4.0.1) all of which I have tried and received the NoClassDefFoundError.

There is no mention of a Gradle version required in the Guava documentation

Is Guava incompatible with newer versions of Gradle?


Solution

  • The reason behind such behavior lies in your classpath. Compile time classpath is different than classpath for runtime. You pass guava to javac but you don't have it available at runtime.

    Very good explanation of quite a similar issue is here: NoClassDefFoundError at Runtime with Gradle. I can't reproduce this issue locally. Consider going to your gradle cache and remove everything.