IntelliJ新建Java项目出现LinkageError,gradle run可正常运行
解决IntelliJ IDEA中Gradle Java项目运行报LinkageError的问题
我通过gradle init --use-defaults --type java-application命令在IntelliJ IDEA中创建了Java应用项目,尝试在IDE内构建并运行时出现以下错误:
LinkageError occurred while loading main class org.example.App
任务:app:App.main()执行失败,Java进程退出值为1
但使用终端命令gradle run可以正常运行项目。我已经尝试修改IDEA中的Java版本、设置$JAVA_HOME环境变量,问题仍未解决。
项目配置文件如下:
build.gradle.kts
/* * This file was generated by the Gradle 'init' task. * * This generated file contains a sample Java application project to get you started. * For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.6/userguide/building_java_projects.html in the Gradle documentation. */ plugins { // Apply the application plugin to add support for building a CLI application in Java. application } repositories { // Use Maven Central for resolving dependencies. mavenCentral() } dependencies { // Use JUnit Jupiter for testing. testImplementation(libs.junit.jupiter) testRuntimeOnly("org.junit.platform:junit-platform-launcher") // This dependency is used by the application. implementation(libs.guava) } // Apply a specific Java toolchain to ease working on different environments. java { toolchain { languageVersion = JavaLanguageVersion.of(21) } } application { // Define the main class for the application. mainClass = "org.example.App" } tasks.named<Test>("test") { // Use JUnit Platform for unit tests. useJUnitPlatform() }
settings.build.kts
/* * This file was generated by the Gradle 'init' task. * * The settings file is used to specify which projects to include in your build. * For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.6/userguide/multi_project_builds.html in the Gradle documentation. */ plugins { // Apply the foojay-resolver plugin to allow automatic download of JDKs id("org.gradle.toolchains.foojay-resolver-convention") version "0.7.0" } rootProject.name = "educationproject-ml" include("app")
可行的解决方法
1. 让IDEA对齐Gradle的Java Toolchain配置
项目中已经通过Java Toolchain指定使用JDK21,IDEA可能未同步该配置:
- 打开
File > Settings > Build, Execution, Deployment > Build Tools > Gradle - 在
Gradle JVM选项中选择Use Gradle from 'gradle-wrapper.properties' file and Java from Toolchain - 点击「Apply」保存,随后点击右上角的Gradle同步按钮重新同步项目
2. 清理缓存并重启
- 清理IDEA缓存:
File > Invalidate Caches...,选择「Invalidate and Restart」 - 清理Gradle缓存:删除项目根目录下的
.gradle文件夹,之后在终端执行gradle build,再回到IDEA尝试运行
3. 检查模块与项目的SDK配置
- 打开
File > Project Structure > Modules,选中app模块:- 「Sources」标签页确认
Language level为21 - 「Dependencies」标签页确认
Module SDK为JDK21
- 「Sources」标签页确认
- 同时检查
File > Project Structure > Project中的Project SDK和Project language level均设置为21
4. 重新导入项目
如果以上方法无效,删除项目根目录下的.idea文件夹和app.iml文件,然后通过File > Open选择项目根目录的build.gradle.kts文件,选择「Open as Project」重新导入。
内容的提问来源于stack exchange,提问作者leichner
相关产品推荐
相关产品推荐

