使用 Guava 类 时出现 NoClassDefFoundError,即使 Guava 包含在 Gradle 构建文件和类路径中

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

当我用 Gradle 构建我的 Guava 依赖项目时使用:

//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"
}

当 运行 Intellij 中的项目时,我得到以下运行时错误:

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

库肯定在类路径中,我不明白为什么会这样。

我已经通过切换到较旧的 Gradle 版本解决了这个问题(3.1、3.2、3.3 都可以)。

因此,我认为问题在于 Gradle 3.4+(3.4、3.5.1、4.0 和 4.0.1),所有这些我都尝试过并收到 NoClassDefFoundError。

Guava documentation

中没有提到需要 Gradle 版本

Guava 是否与更新版本的 Gradle 不兼容?

这种行为背后的原因在于您的类路径。编译时类路径与运行时类路径不同。您将 guava 传递给 javac,但在运行时它不可用。

这里有一个非常相似的问题的很好的解释:。我无法在本地重现此问题。考虑前往 gradle 缓存并删除所有内容。

问题出在我使用的 Intellij 版本 (2016.3.1)

一旦我将 Intellij 更新到 2016.3.7,项目就可以在 Gradle 的所有版本上正常运行。