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

标签 java exception exception-handling kotlin

我正在开发一个 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 block 。我创建这个 Kotlin 类的实例有什么问题吗?

更新2:
我用 Throwable 添加了第二个 catch block ,并捕获了以下 Throwable。

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

更新3:
将标题更改为更正错误并修复了将所有项目文件添加到 jar 的问题(请参见下面的答案)。 将 Kotlin 运行时库添加到 gradle 对我不起作用。

最佳答案

将所有项目文件添加到 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) } }
}

更新:根据 thisconfigurations.compile.collect 更改为 configurations.compileClasspath.collect在下面回答。

关于java - Gradle 项目 : java. lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44197521/

相关文章:

java - 有没有更好的解决方案来获取重复项并在数组中计数?

Java Swing动画重影问题

asp.net - ASPX 服务器异常

c# - 是否可以在某些场景中吞下除关键异常之外的所有异常?

PHP 5.5 并尝试......终于

java - 比较流口水中的日期

java - 使用计数器将数组插入到 HashMap 中

exception - 如何使用 ScalaTest 测试预期异常的其他属性

c# - 在 IDE 外部运行时为 “Index was outside the bounds of the array”

asp.net-mvc-3 - ASP.NET MVC 中全局错误/异常处理的最佳实践是什么?