Compile and execute a JDK preview feature with Maven
Step 1
One can make use of the following maven configurations to compile the code using the --enable-preview
along with --release 12
+ (e.g. 13
, 14
, 15
) argument.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>12</release> <!-- <release>13/14/15</release> -->
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<!-- This is just to make sure the class is set as main class to execute from the jar-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>edu.forty.bits.expression.SwitchExpressions</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Note:- I had to also ensure on my MacOS that my ~/.mavenrc
file was configured to mark java 13 as the default java configured for maven.
Step 2
Execute the maven command to build the jar from the module classes
mvn clean verify
Step 3
Use the command line to execute the main class of the jar created in the previous step as :
java --enable-preview -jar target/forty-bits-of-java-1.0.0-SNAPSHOT.jar
the last argument is the path to the jar built by maven.
This produces the output as expected as:
(screenshot is from a previous execution.)
Source on GitHub
Edit: A learning from an unwanted debugging session, use the arguments in the format as follows:
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
Reason being, if you specify two different arguments it doesn't fail during the configuration validation and the one found later overrules the effective config:
<compilerArgs>--enable-preview</compilerArgs>
<compilerArgs>-Xlint:all</compilerArgs>
To enable preview feature you must define --enable-preview in pom.xml under compilerArgs
in below I mention how to enable preview feature with java 13.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>13</release>
<compilerArgs>
--enable-preview
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>