java - Gradle 项目 : java. lang.NoClassDefFoundError

我正在开发一个 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) } }
}

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

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

相关文章:

kotlin - Kotlin 中的静态数据

kotlin - 在 Kotlin 中处理可为空或空列表的惯用方式

java - Kotlin 数据类实现 Java 接口(interface)

regex - 使用正则表达式在 Kotlin 中进行 URL 解析

android - 监听器绑定(bind);找不到二传手

java - 如何从 Kotlin/Java 中运行 Kotlin-Script (.kts) 文件

android - Kotlin - 如何在 ViewPager 中添加 OnPageChangeL

android - 更新到 AS 3.0 Canary 6 后 transformClassesWi

kotlin - 在 Kotlin 中带有参数的单例

arrays - Kotlin 中的二维 Int 数组