Exec java goal with toolchain can not enable preview features

Viewed 16

I want to taste the newest Java 19 feature, also do not change the default Java Home( Java 17).

So I create a toolchain.xml in the ~/.m2, and define a jdk type toolchain like this.

<toolchain>
    <type>jdk</type>
    <provides>
      <version>19</version>
      <vendor>oracle</vendor>
    </provides>
    <configuration>
      <jdkHome>D:/jdks/jdk-19</jdkHome>
    </configuration>
</toolchain>

Then I added the following plugins in my project POM.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.10.1</version>
    <configuration>
        <compilerArgs>
            <arg>--enable-preview</arg>             
        </compilerArgs>
        <encoding>${project.build.sourceEncoding}</encoding>
    </configuration>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-toolchains-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <goals>
                <goal>toolchain</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <toolchains>
            <jdk>
                <version>19</version>
                <vendor>oracle</vendor>
            </jdk>
        </toolchains>
    </configuration>
</plugin>
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <mainClass>com.example.demo.RecordPatternExample</mainClass>
        <commandlineArgs>--enable-preview</commandlineArgs>
        <arguments>
            <argument>--enable-preview</argument>
        </arguments>
    </configuration>
</plugin>

As suggested in this question, I also added --enable-preview to the .mvn/jvm.config.

But when running the project in command line.

mvn clean package exec:java

I still got the exception like this.

[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.1.0:java (default-cli) 
on project record-pattern: An exception occurred while executing the Java class. 
com/example/demo/RecordPatternExample has been compiled by a more recent version of the Java Runtime (class file version 63.65535),
 this version of the Java Runtime only recognizes class file versions up to 61.0 -> [Help 1]

Obvisouly the --enable-preview option was not applied with exec:java, but it worked well with maven-compiler-plugin.

The sample project is shared on my Github.

0 Answers
Related