How can I run a Java class inside a Maven artifact, automatically resolving dependencies?
dependencies, java, maven
Solution
There is no out-of-the-box solution for your task. But you can create a simple script to solve it:
- Download pom.xml of your tool from the repo.
- Download jar of your tool.
- Download all its dependencies.
- Run java against resolved libraries.
Command line:
> mvn dependency:copy -Dartifact=<tool.group.id>:<tool.artifact.id>:<tool.version>:pom -DoutputDirectory=target
> mvn dependency:copy -Dartifact=<tool.group.id>:<tool.artifact.id>:<tool.version> -DoutputDirectory=target
> mvn dependency:copy-dependencies -f target/<tool.artifact.id>-<tool.version>.pom -DoutputDirectory=target
> java -cp target/* <tool.main.class>
Directory ./target will contain your tool + all dependencies.
See details on dependency:copy and dependency:copy-dependencies mojos.
Edit
As alternative, you can build classpath using libraries in the local repo by:
> mvn dependency:build-classpath -DincludeScope=runtime -f target/<tool.artifact.id>-<tool.version>.pom [-Dmdep.outputFile=/full/path/to/file]
See details on build-classpath mojo.
Problem
If I know the coordinates of an artifact, and a name of the class inside that artifact, can I make Maven run the class, including all of its dependencies on the Java classpath? For example, suppose a coworker told me about a tool I can run, which is published to our internal Nexus with the artifact coordinates `example:cool-tools:1.0.0`. I used this answer to download the artifact. Now, I know that the main class name is `example.Main`. But if I just go to the artifact's download location and run `java -cp cool-tools-1.0.0.jar example.Main`, I get `NoClassDefFoundError`s for any dependencies of `cool-tools`. I'm aware of the `maven-exec-plugin`, but as far as I can tell that's only for projects where you have the source. Suppose I don't have access to the source, only the Nexus containing the tool (and all its dependencies). Ideally, I'd do something like `mvn exec:exec -DmainArtifact='example:cool-tools:1.0.0' -DmainClass='example.Main'`, but I don't think the exec plugin is actually capable of this. ETA: To be clear, I do not have a local project / POM. I want to do this using only the command line, without writing a POM, if possible.