4

It's easy to compile your Java sources with --enable-preview:

<!-- 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 then run exec:java? Using

<!-- 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>

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'
Naman
  • 27,789
  • 26
  • 218
  • 353
kantianethics
  • 671
  • 5
  • 21
  • 1
    During the time when Java-12 was in development, I remember trying this out with the shade plugin creating a jar and executing using the java command line, the steps for that are listed [under this Q&A](https://stackoverflow.com/questions/52232681/compile-and-execute-a-jdk-preview-feature-with-maven). – Naman Mar 30 '20 at 03:07

1 Answers1

4

The problem is that exec:java runs in the same maven java process, which by default isn't started with --enable-preview.

You could instead switch to exec:exec, but one way to still use exec:java is to create a .mvn/jvm.config file containing --enable-preview. You can put this in your project's root directory and check into git. Or create a MVN_OPS environment variable.

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

kantianethics
  • 671
  • 5
  • 21
  • I have tried this approach with toolchain, it did not work, https://stackoverflow.com/questions/73830548/exec-java-goal-with-toolchain-can-not-enable-preview-features – Hantsy Sep 24 '22 at 03:05