In this short post, we share our solution for adding an incubated module to the execution of a Maven project.

Problem

We would like to execute a Maven project directly using the maven-exec-plugin and the command mvn exec:java. Therefore, we add the following plugin to our pom.xml file:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <mainClass>package.MainClass</mainClass>
    </configuration>
</plugin>

However, the command mvn exec:java results in the following error:

java.lang.NoClassDefFoundError: jdk/incubator/vector/DoubleVector
    at package.MainClass.mainMethod (MainClass.java:13)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:279)
    at java.lang.Thread.run (Thread.java:840)
Caused by: java.lang.ClassNotFoundException: jdk.incubator.vector.DoubleVector
    at org.codehaus.mojo.exec.URLClassLoaderBuilder$ExecJavaClassLoader.loadClass (URLClassLoaderBuilder.java:198)
    at java.lang.ClassLoader.loadClass (ClassLoader.java:525)
    at package.MainClass.mainMethod (MainClass.java:13)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:279)
    at java.lang.Thread.run (Thread.java:840)

This is because the project requires an incubated module, i.e., jdk.incubator.vector in our case. These incubated modules must be added explicitly, e.g., to the Maven compiler by adding the following compiler arguments to the plugin configuration:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.11.0</version>
    <configuration>
    <compilerArgs>
        <arg>--add-modules=jdk.incubator.vector</arg>
    </compilerArgs>
    </configuration>
</plugin>

However, doing it similar for the exec-maven-plugin did not work for us.

Solution

After several attempts of adding the module to the exec-maven-plugin configuration or similar, we came up with the following working solution. It is possible to pass certain options to Maven via the environment variable MAVEN_OPTS. Passing the option for adding the incubated module through this environment variable resolved the problem for us. Thus, the final command for executing the Maven project eventually is the following:

MAVEN_OPTS=--add-modules=jdk.incubator.vector mvn exec:java

References

The thread Maven Exec Plugin with Preview Features on StackOverflow helped in finding this solution. Many thanks to the user kantianethics for asking and answering this question.