You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在命令行运行交互式Kotlin JVM程序并解决主类缺失问题

问题:无法运行Kotlin JVM命令行应用

我的Kotlin JVM应用在IntelliJ内置Shell中可正常交互运行,但通过命令行运行或分发时出现错误,程序仅使用readln()函数。

代码与构建配置

Kotlin主代码

package com.xingpeds

fun main() {
    val name = readln()
    println("Hello, " + name + "!")
}

Gradle构建文件

plugins {
    kotlin("jvm") version "2.0.20"
    application
}
application {
    mainClass.set("MainKt")
}
group = "com.xingpeds"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test"))
}

tasks.test {
    useJUnitPlatform()
}
kotlin {
    jvmToolchain(19)
}

错误信息

执行./gradlew clean run时输出错误:

euclid@kyles-MBP-3 ~/D/democli (main)> ./gradlew clean run

> Task :run FAILED
Error: Could not find or load main class MainKt
Caused by: java.lang.ClassNotFoundException: MainKt

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':run'.
> Process 'command '/Users/euclid/Library/Java/JavaVirtualMachines/corretto-19.0.2/Contents/Home/bin/java'' finished with non-zero exit value 1

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.

BUILD FAILED in 545ms
3 actionable tasks: 3 executed

运行构建生成的脚本build/scripts/democli时同样报错:

euclid@kyles-MBP-3 ~/D/democli (main)> build/scripts/democli
Error: Could not find or load main class MainKt
Caused by: java.lang.ClassNotFoundException: MainKt

解决方法

核心问题:主类配置错误

你的main函数位于com.xingpeds包下,Kotlin会将顶层函数编译为包名.MainKt格式的类,因此Gradle中配置的主类必须包含完整包路径,而非仅MainKt。

步骤1:修正Gradle主类配置

修改构建文件中的application块,将mainClass设置为完整类名:

application {
    mainClass.set("com.xingpeds.MainKt")
}

步骤2:重新运行或构建

  • 直接运行程序:执行./gradlew clean run,此时程序可正常读取命令行输入
  • 构建可分发的本地脚本:执行./gradlew clean installDist,生成的脚本位于build/install/[你的项目名]/bin/目录下,直接运行该脚本即可

可选:构建可独立运行的Jar包

如果需要分发单个可运行Jar包,可使用shadowJar插件构建包含所有依赖的fat jar:

  1. 在构建文件的plugins块中添加插件:
plugins {
    kotlin("jvm") version "2.0.20"
    application
    id("com.github.johnrengelman.shadow") version "8.1.1"
}
  1. 执行构建命令:./gradlew shadowJar
  2. 运行生成的Jar包:java -jar build/libs/[项目名]-1.0-SNAPSHOT-all.jar

内容的提问来源于stack exchange,提问作者Kyle M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:01:14