Gradle 中添加生成 jar 报错

plugins { kotlin("jvm") version "2.1.20" application } group = "org.example" version = "1.0-SNAPSHOT" repositories { mavenCentral() } dependencies { testImplementation(kotlin("test")) } tasks.test { useJUnitPlatform() } kotlin { jvmToolchain(22) } application { mainClass.set("org.example.MainKt") // 替换成你的主类 } 我这样写仍然提示错误:<html>Unresolved reference. None of the following candidates is applicable because of a receiver type mismatch:<br/>val PluginDependenciesSpec.application: PluginDependencySpec

✅ 快速检查:

  • application 插件有没有加在 plugins {} 中?

  • application { ... } 配置块是不是放在文件底部?

  • mainClass.set(...) 是不是指向了正确的类(以 .kt 结尾的类名 + 包路径)?

非常明确了 ✅------你遇到这个问题是因为在你的 build.gradle.kts 文件中,IDE(如 IntelliJ IDEA)提示 application 是 unresolved reference,但你写法其实已经是 ✅ 正确的。


🔍 原因(解释这个奇怪的现象)

你看到的错误提示其实来源于 IDE 的提示系统(可能是语法分析/索引的问题),而不是 Gradle 本身的语法错误。

这个是 IntelliJ 的一个已知问题,尤其在以下几种场景下很常见:

  • 刚升级 Kotlin 插件/Gradle 版本

  • kotlin-dsl 项目在缓存未重建时提示错误

  • 使用了较新的 Kotlin 版本(比如你用了 2.1.20


✅ 解决方法

  1. 刷新 Gradle 项目(最有效)

    • IntelliJ IDEA 左侧 Gradle 面板 → 点击刷新按钮(🔁)

    • 或者菜单栏 File > Sync Project with Gradle Files

  2. Invalidate Caches and Restart

    • 菜单栏 File > Invalidate Caches / Restart → 选择 Invalidate and Restart
  3. 确保你用了 build.gradle.kts(不是 build.gradle

    • 因为 application {} 是 Kotlin DSL 的语法,如果你用 Groovy 的 .gradle 文件,它不识别 mainClass.set(...) 的 Kotlin 语法
  4. 检查 Gradle Wrapper 的版本

    • 打开 gradle/wrapper/gradle-wrapper.properties,确保你用的是比较新的 Gradle,比如:

      复制代码

      properties

      复制代码

      distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip

    • Kotlin 2.1.20 需要较新版本的 Gradle 才能完全兼容。


🧪 最终验证:运行构建

不管 IDE 有没有报红,你可以在项目根目录执行:

复制代码

bash

复制代码

./gradlew build

或者直接运行 JAR:

复制代码

bash

复制代码

./gradlew run

只要这两个命令成功,说明你的 application 配置是完全正确的,IDE 报红可以暂时无视。

" .\gradlew.bat clean build"

生成jar

相关推荐
佛祖保佑永不宕机6 小时前
maven引入本地jar包
java·maven·jar
移动开发者1号10 小时前
使用 Android App Bundle 极致压缩应用体积
android·kotlin
移动开发者1号10 小时前
构建高可用线上性能监控体系:从原理到实战
android·kotlin
恋猫de小郭20 小时前
Meta 宣布加入 Kotlin 基金会,将为 Kotlin 和 Android 生态提供全新支持
android·开发语言·ios·kotlin
androidwork1 天前
深入解析内存抖动:定位与修复实战(Kotlin版)
android·kotlin
heeheeai1 天前
kotlin 通道trysend方法
android·开发语言·kotlin
用户5248034919911 天前
Gradle 镜像地址设置
gradle
移动开发者1号1 天前
ReLinker优化So库加载指南
android·kotlin
移动开发者1号1 天前
剖析 Systrace:定位 UI 线程阻塞的终极指南
android·kotlin
移动开发者1号1 天前
深入解析内存抖动:定位与修复实战(Kotlin版)
android·kotlin