NetBeans 13中Maven项目无法运行Hello World的问题求助
Maven项目无法找到主类的解决方法
环境与问题场景
使用NetBeans IDE 13 + JDK 15.0.1开发Maven版HelloWorld项目,代码无语法错误,但运行时提示找不到主类。
项目代码
Java主类代码:
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Project/Maven2/JavaApp/src/main/java/${packagePath}/${mainClassName}.java to edit this template */ package com.mycompany.testing; /** * * @author Lenovo */ public class Testing { public static void main(String[] args) { System.out.println("Hello World!"); } }
pom.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mycompany.testing</groupId> <artifactId>Testing</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>15</maven.compiler.source> <maven.compiler.target>15</maven.compiler.target> <exec.mainClass>com.mycompany.testing.Testing</exec.mainClass> </properties> </project>
错误信息
运行时核心错误:
Error: Could not find or load main class com.mycompany.testing.Testing Caused by: java.lang.ClassNotFoundException: com.mycompany.testing.Testing Command execution failed.
伴随Maven插件执行失败:
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.0.0:exec (default-cli) on project Testing: Command execution failed.: Process exited with an error: 1 (Exit value: 1)
解决步骤
1. 确保项目已正确编译
- 在NetBeans终端执行命令:
mvn clean compile,强制重新编译项目,排查是否有隐藏编译错误。 - 检查项目目录下的
target/classes/com/mycompany/testing/路径,确认存在Testing.class文件。如果没有,说明编译未完成,需先解决编译问题。
2. 关闭NetBeans的「编译时保存」功能
错误日志显示Running NetBeans Compile On Save execution. Phase execution is skipped,该功能可能导致编译产物未正确生成:
- 右键项目 → 属性 → 构建 → 编译,取消勾选「编译时保存」选项。
- 执行
mvn clean install重新构建,再尝试运行项目。
3. 显式配置exec-maven-plugin
NetBeans自动调用插件可能存在参数问题,在pom.xml中添加插件的显式配置:
<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.0.0</version> <configuration> <mainClass>com.mycompany.testing.Testing</mainClass> </configuration> </plugin> </plugins> </build>
添加后,可在终端用mvn exec:java命令运行,或直接使用NetBeans的运行按钮。
4. 修复项目路径的特殊字符
项目路径中存在全角斜杠╱,可能导致Maven无法正确解析路径:
- 将路径中的
╱替换为半角斜杠/或\,确保路径仅包含普通字符。 - 重新导入项目或直接修改路径后,重新运行。
5. 验证JDK与Maven配置
- 打开NetBeans的「工具 → Java平台」,确认选中的是JDK 15.0.1,路径正确。
- 检查「工具 → Maven → 执行」,确认Maven使用的JAVA_HOME指向正确的JDK目录。
内容的提问来源于stack exchange,提问作者Amir Haziq
相关产品推荐
相关产品推荐

