Stéphane GRILLON
Stéphane GRILLON

Reputation: 11864

How to execute a java main class from the command line

My class:

package com.your.company.cli;

import com.github.domain.cli.Cli;
import com.your.company.utils.MySuperClass;

public class Hello {
    public static void main(String[] args) throws TechnicalException {
        new Cli().runcli(MySuperClass.class, args);
    }
}

On my Eclipse is OK:

enter image description here

I need run my class by a command line. (after compile by Maven (mvn clean install))

java -cp .... ???? com.your.company.cli.Hello ... ???

EDIT 1:

I try java -jar myproject.jar

aucun attribut manifest principal dans myproject.jar

I try java -cp myproject.jar com.your.company.cli.Hello

impossible de trouver la classe principale com.your.company.cli.Hello

EDIT 2:

I try add maven-jar-plugin but my result is a Maven jar (not a fat jar). I looking for a solution with commande line without jar file please (juste the same behavior as on Eclipse).

Upvotes: 0

Views: 4538

Answers (2)

Elarbi Mohamed Aymen
Elarbi Mohamed Aymen

Reputation: 1700

  • You can launch the jar file created with java -jar /target/myproject.jar.

  • You cannot use java -cp ... or javac because you need to put all java files in the same folder to be compiled.

  • For the error aucun attribut manifest principal dans myproject.jar is generated because java could not find main class i advise you to add this to your pom.xml file

`

<build>
  <plugins>
    <plugin>
      <!-- Build an executable JAR -->
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>3.0.2</version>
      <configuration>
        <archive>
          <manifest>
            <addClasspath>true</addClasspath>
            <classpathPrefix>lib/</classpathPrefix>
            <mainClass>com.mypackage.MyClass</mainClass>
          </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>
</build>

and mention full name of your main class

[UPDATE]

  • In case you have multiple dependecies and you want to include all of them with your final jar you can use maven-assembly-plugin like this :

    <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <archive> <manifest> <mainClass>${mainClass}</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </execution> </executions> </plugin>

you must replace ${mainClass} with your main class full name

Upvotes: 0

St&#233;phane GRILLON
St&#233;phane GRILLON

Reputation: 11864

I find solution without modify my project:

mvn clean install
mvn exec:java -Dexec.mainClass=com.your.company.cli.Hello

Upvotes: 5

Related Questions