Gradle 项目:java.lang.NoClassDefFoundError:kotlin/jvm/internal/Intrinsics

新手上路,请多包涵

我正在做一个 Java 项目,在这个项目中我第一次尝试使用 Kotlin。我开始使用 Intellij Idea 中提供的 JavaToKoltin 转换器将一些类转换为 Kotlin。除其他外,我的自定义异常现在已转换为 Kotlin。但是有了这个,异常处理就不再正确了。

如果我在 java 代码中抛出我的自定义异常之一(例如 MyCustomKotlinException.kt ),则不会捕获该异常(请参见下面的代码)。

 // Example.java
package foo

import java.util.*;
import java.lang.*;
import java.io.*;
import foo.MyCustomKotlinException;

class Example
{
    public static void main (String[] args)
    {
        try {
            // Do some stuff
            // if Error
            MyCustomKotlinException e = new MyCustomKotlinException("Error Message");
            throw e;
        } catch (MyCustomKotlinException e) {  // <-- THIS PART IS NEVER REACHED
            // Handle Exception
        } catch (Throwable e) {
            e.printStackTrace(); <-- This is catched
        } finally {
            // Finally ...
        }
    }
}

所以任何人都可以向我解释为什么没有捕获异常。 MyCustomKotlinException 继承自 Kotlins RuntimeException ,它只是 java.lang.RuntimeException 的别名。

 // MyCustomKotlinException.kt
package foo

class MyCustomKotlinException(err: String) : RuntimeException(err)

更新:

我将throw部分拆分成2行(实例创建和throwing),发现问题不在throwing。 try 块在实例创建后留下。我创建这个 Kotlin 类的实例有什么问题吗?

更新2:

我添加了第二个 catch 块 Throwable 并捕获了以下 Throwable。

 java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
...
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics

更新3:

更改了标题以更正错误并解决了将所有项目文件添加到 jar 的问题(请参阅下面的答案)。将 Kotlin 运行时库添加到 gradle 对我不起作用。

原文由 FreshD 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.8k
2 个回答

将所有项目文件添加到 jar 对我来说解决了这个问题。我将以下行添加到我的 build.gradle

 jar {
    manifest {
        attributes ...
    }
    // This line of code recursively collects and copies all of a project's files
    // and adds them to the JAR itself. One can extend this task, to skip certain
    // files or particular types at will
    from { configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
}

更新:根据下面 答案将 configurations.compile.collect 更改为 configurations.compileClasspath.collect

原文由 FreshD 发布,翻译遵循 CC BY-SA 4.0 许可协议

您需要使用 kotlin 配置您的项目。所以在 Android Studio 中:

  1. 单击工具 => kotlin => 在项目中配置 kotlin

  2. 然后在对话框中检查:All module containing kotlin files

  3. 并选择版本

  4. 按确定

完毕。

原文由 Suraj Vaishnav 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题