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

如何用Maven从命令行运行非标准路径下的Java主类?

解决Maven执行非默认源目录下主类的ClassNotFound问题

问题根源分析

你遇到的ClassNotFoundException主要有两个核心原因:

  1. 错误使用文件路径而非全限定类名:mvn exec:java的-Dexec.mainClass参数需要的是类的全限定类名(包名+类名),不是文件系统路径,你写的src.communication.Launcher.Launcher是路径格式,完全不符合插件要求。
  2. Maven未识别自定义源目录:Maven默认只编译src/main/java下的代码,你的源文件夹src/communication不在默认编译列表里,所以Maven根本没处理这个目录下的Launcher.java,自然找不到编译后的类文件。

解决方案

方案一:临时命令行快速执行(适合临时测试场景)

先让Maven编译你的自定义源目录,再执行主类:

  1. 编译src/communication下的代码(JDK版本根据你的实际环境调整,比如换成11/17):
mvn compile -Dmaven.compiler.source=1.8 -Dmaven.compiler.target=1.8 -Dmaven.compiler.srcDirs=src/communication
  1. 执行主类,这里用全限定类名Launcher.Launcher(因为src/communication是源根,里面的Launcher文件夹对应包名,类名也是Launcher):
mvn exec:java -Dexec.mainClass=Launcher.Launcher -Dexec.classpathScope=compile

也可以把两步合并成一条命令:

mvn compile exec:java -Dmaven.compiler.srcDirs=src/communication -Dexec.mainClass=Launcher.Launcher -Dexec.classpathScope=compile

方案二:修改pom.xml配置源目录(推荐,符合Maven规范)

如果这个源目录是长期使用的,最好把它配置到pom.xml里,让Maven默认识别:
在你的pom.xml中添加<build>节点下的<sources>配置:

<build>
    <sources>
        <!-- 添加上你的自定义源目录 -->
        <source>src/communication</source>
        <!-- 如果还有默认的src/main/java目录需要保留,也可以加上 -->
        <!-- <source>src/main/java</source> -->
    </sources>
</build>

配置完成后,只需要执行这条简单命令就能运行主类:

mvn compile exec:java -Dexec.mainClass=Launcher.Launcher

额外检查点

确保你的Launcher.java里的包声明是正确的:

package Launcher; // 因为src/communication是源根,里面的Launcher文件夹对应这个包名

public class Launcher {
    public static void main(String[] args) {
        // 你的业务代码
    }
}

如果你的包声明是package communication.Launcher;,那说明你的源根应该是src而不是src/communication,这时候全限定类名要改成communication.Launcher.Launcher,同时调整pom.xml的源目录为<source>src</source>。

内容的提问来源于stack exchange,提问作者aditya rawat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:38:19