Java – Maven Exec plugin with preview capabilities

Maven Exec plugin with preview capabilities… here is a solution to the problem.

Maven Exec plugin with preview capabilities

Compiling Java source code with —enable-preview is easy:

<!-- Enable preview features -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <release>15</release>
        <compilerArgs>--enable-preview</compilerArgs>
    </configuration>
</plugin>

But how can you run exec:java? Use

<!-- Exec plugin.. run with `mvn exec:java` -->
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.6.0</version>
    <configuration>
        <mainClass>${mainClass}</mainClass>
        <commandlineArgs>--enable-preview</commandlineArgs>
        <arguments>
            <argument>--enable-preview</argument>
        </arguments>
        </systemProperties>
    </configuration>
</plugin>

It still results in the following error:

An exception occured while executing the Java class. 
Preview features are not enabled for Main (class file version 59.65535). 
Try running with '--enable-preview'

Solution

The problem is exec: Java runs in the same Maven Java process, and it is not started with —enable-preview by default.

One way you can switch to exec:exec

instead, but still use exec:java, is to create an . mvn/jvm.config file that contains -- enable preview. You can put it in the root directory of the project and check it into git. Or create an MVN_OPS environment variable.

Quote: https://maven.apache.org/configure.html

Related Problems and Solutions