Home > database >  "Could not find or load main class" from executing JAR generated in 'mvn install'
"Could not find or load main class" from executing JAR generated in 'mvn install'

Time:10-28

I'm trying to generate a JAR file from Groovy code with Maven. It works well, the classes are in the jar file, but it gives me the error 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>

I took this from Groovy docs.

Tree:

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

Main.groovy:

package me.strafe.hello

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

I've tried with gradle too, but i wasn't so familiar with it since i've used maven before.

CodePudding user response:

If you run the program like this, it will work:

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

Make sure to add any other jars (like the groovy jars) to the classpath, something like this (the file separator is : on Linux, ; on Windows):

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

You can also configure the POM to generate a "fat jar" that includes the dependencies inside a single jar, to make this easier.

If you really want your jar to be runnable, then you should do as above, but also add the Main-Class declaration to the jar's manifest so that you don't need to specify the main class in the command line as shown above.

Once you do both of those things (fat jar and Main-Class declared in the Manifest) this command will also work:

java -jar my.jar
  • Related