Search code examples
javaeclipsemavenclasspathjunit4

How do I run a single class after compiling the whole project with maven in command line?


I was able to run this in Eclipse but have problem running it with command line.

My main java class that I want to run is Example.java (inside src/main/java/examples)
Note that although there is a simple junit test in the main Example.java I don’t want to have any tests associated with the java file in src/test/java )

First I cd to the directory where pom.xml is

cd pathToTheProject/projectname

I do the following:

mvn clean
mvn compile
mvn package

Now to only run the main class called Example.class I write the following (I suppose pathToMavenLib/.m2/repository/* contains all the jar files needed):

java -cp "pathToMavenLib/.m2/repository/*" examples.Example

But this gives me error: Error: Could not find or load main class examples.Example

Edit:
I solve my problem using mvn exec:java -Dexec.mainClass="org.junit.runner.JUnitCore" -Dexec.arguments="examples.Example"


Solution

  • You can create a deployable artifact as war file (By changing packaging to war using <packaging>war</packaging>) that will contain all the dependent jar files under its lib directory.
    You can then run: mvn clean install

    You can then extract it and run your class file directly by giving class-path parameter.

    Other option is to use maven run plugin - mvn exec:java -Dexec.mainClass="com.example.Main" [-Dexec.args="argument1"] ...

    reference: Maven Run Project