首页 > 解决方案 > “无法找到或加载主类”从执行“mvn install”中生成的 JAR

问题描述

我正在尝试使用 Maven 从 Groovy 代码生成 JAR 文件。它运行良好,类在 jar 文件中,但它给了我错误Error: Could not find or load main class me.strafe.hello.Main

pom.xml

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-antrun-plugin</artifactId>
        <executions>
          <execution>
            <id>compile</id>
            <phase>compile</phase>
            <configuration>
              <tasks>
                <mkdir dir="${basedir}/src/main/groovy"/>
                <taskdef name="groovyc"
                         classname="org.codehaus.groovy.ant.Groovyc">
                <classpath refid="maven.compile.classpath"/>
              </taskdef>
              <mkdir dir="${project.build.outputDirectory}"/>
              <groovyc destdir="${project.build.outputDirectory}"
                       srcdir="${basedir}/src/main/groovy/"
                       listfiles="true">
              <classpath refid="maven.compile.classpath"/>
            </groovyc>
          </tasks>
        </configuration>
        <goals>
          <goal>run</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>me.strafe.hello.Main</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>

我从 Groovy 文档中获取了这个。

树:

├── pom.xml
├── src
│   └── main
│       └── groovy
│           └── Main.groovy

Main.groovy:

package me.strafe.hello

class Main {
  static void main(String[] args) {
    println "Hello, World!"
  }
}

我也尝试过使用 gradle,但我对它不太熟悉,因为我以前使用过 maven。

标签: mavengroovyjar

解决方案


如果你像这样运行程序,它将工作:

java -cp my.jar me.strafe.hello.Main

确保将任何其他 jars(如 groovy jars)添加到类路径中,如下所示(文件分隔符:在 Linux 上,;在 Windows 上):

java -cp libs/groovy-all.jar:my.jar me.strafe.hello.Main

您还可以将 POM 配置为生成一个“胖 jar”,其中包含单个 jar 中的依赖项,以使其更容易。

如果你真的希望你的 jar 是可运行的,那么你应该像上面那样做,但还要Main-Class声明添加到 jar 的清单中,这样你就不需要在命令行中指定主类,如上所示。

一旦你做了这两件事(fat jar 和在 Manifest 中声明的 Main-Class),这个命令也将起作用:

java -jar my.jar

推荐阅读