With JDK/12 EarlyAccess Build 10, the JEP-325 Switch Expressions has been integrated as a preview feature in the JDK. A sample code for the expressions (as in the JEP as well):
Scanner scanner = new Scanner(System.in);
Day day = Day.valueOf(scanner.next());
switch (day) {
case MONDAY, TUESDAY -> System.out.println("Back to work.") ;
case WEDNESDAY -> System.out.println("Wait for the end of week...") ;
case THURSDAY,FRIDAY -> System.out.println("Plan for the weekend?");
case SATURDAY, SUNDAY -> System.out.println("Enjoy the holiday!");
}
where Day
being an enum as
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
The Preview Language and VM Features JEP-12 already elaborate how a feature can be enabled during compile and runtime using javac
and java
.
How can one try out this feature using Maven?
Step 1: One can make use of the following maven configurations to compile the code using the --enable-preview
along with --release 12
argument.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>12</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>com.stackoverflow.nullpointer.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 12 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/jdk12-updates-1.0.0-SNAPSHOT.jar #the last argument being the path to my jar
This produces the output as expected as:
来源:https://stackoverflow.com/questions/52232681/compile-a-jdk12-preview-feature-with-maven