In Maven, how output the classpath being used?

To get the classpath all by itself in a file, you can:

mvn dependency:build-classpath -Dmdep.outputFile=cp.txt

Or add this to the POM.XML:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.9</version>
        <executions>
          <execution>
            <id>build-classpath</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>build-classpath</goal>
            </goals>
            <configuration>
              <!-- configure the plugin here -->
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

From: http://maven.apache.org/plugins/maven-dependency-plugin/usage.html

This command outputs the classpath on Mac and Linux:

mvn -q exec:exec -Dexec.executable=echo -Dexec.args="%classpath"

Having the result printed and not saved into a file might be useful, for instance, when assigning the result to a variable in a Bash script. This solution runs on Mac and Linux only, but so do Bash shell scripts.

In Windows (e.g. in BAT files), where there is no echo executable, you will need something like this (untested):

mvn -q exec:exec -Dexec.executable=cmd -Dexec.args="/c echo %classpath"

Alternatively, you can just execute java program with the classpath:

mvn -q exec:exec -Dexec.executable=java -Dexec.args="-cp %classpath Main"

Or even like that (it will use the correct classpath automatically):

mvn -q exec:java -Dexec.mainClass="Main" 

However, both these alternative approaches suffer from Maven adding its error messages when your program fails.

Leave a Comment