繁体   English   中英

kotlin 和 gradle jar 出现“错误:无法找到或加载主 class”

[英]kotlin with gradle jar got 'Error: Could not find or load main class '

我正在为我的项目使用 gradle 和 kotlin。 当我使用

java -jar qq-bot-0.1.0.jar

我总是得到

Error: Could not find or load main class org.livewatcher.qqbot.Main
Caused by: java.lang.ClassNotFoundException: org.livewatcher.qqbot.Main

这是我的 build.gradle.kts 文件:在此处输入图像描述

这是我的 Main.kt 文件的一部分:在此处输入图像描述

这是我的文件结构:在此处输入图像描述

我正在使用 kotlin 1.7.21 和 jvm 版本是

openjdk version "17.0.2" 2022-01-18
OpenJDK Runtime Environment (build 17.0.2+8-86)
OpenJDK 64-Bit Server VM (build 17.0.2+8-86, mixed mode, sharing)

谁能帮我? 非常感谢!

我尝试将以下代码添加到我的 build.gradle.kts 文件中

tasks.withType<Jar>() {
    manifest {
        attributes["Main-Class"] = "org.livewatcher.qqbot.Main"
    }
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE

    // To add all the dependencies
    from(sourceSets.main.get().output)

    dependsOn(configurations.runtimeClasspath)
    from({
        configurations.runtimeClasspath.get().filter { it.name.endsWith("jar") }.map { zipTree(it) }
    })
}

但它没有用。

结论先行

仅在插件中添加id("io.ktor.plugin") version "2.2.1" plugins {

建造

gradle buildFatJar

跑步

cd build/libs
java -jar DemoKotlinApp-all.jar

示例项目

DemoKotlinApp
├── build.gradle.kts
├── gradle.properties
├── settings.gradle.kts
└── src
    └── main
        └── kotlin
            └── Main.kt

build.gradle.kts

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.7.20"
    application
    id("io.ktor.plugin") version "2.2.1"
}

group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

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

tasks.test {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = "1.8"
}

application {
    mainClass.set("MainKt")
}

gradle.properties

kotlin.code.style=official

设置.gradle.kts

rootProject.name = "DemoKotlinApp"

主要.kt

fun main(args: Array<String>) {
    println("Hello World!")
}

建造

gradle buildFatJar

跑步

cd build/libs
java -jar DemoKotlinApp-all.jar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM