步骤1
可以使用以下Maven配置来编译代码,使用--enable-preview
和--release 12
+(例如13
、14
、15
)参数。
<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>
注意:我还需要在我的MacOS上确保我的~/.mavenrc
文件被配置为将Java 13标记为为Maven配置的默认Java。
步骤2
执行Maven命令以从模块类构建jar包。
mvn clean verify
第三步
使用命令行执行上一步创建的jar包的主类,命令如下:
java --enable-preview -jar target/forty-bits-of-java-1.0.0-SNAPSHOT.jar
{{最后一个参数是Maven构建的JAR文件路径。}}
{{这将产生预期输出:}}
(截图来自上一次执行。)
GitHub上的源代码
编辑:从一次不必要的调试会话中学到的经验,使用以下格式中的参数:
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
原因是,如果您指定了两个不同的参数,则在配置验证期间不会失败,并且后面找到的参数将覆盖有效配置:
<compilerArgs>--enable-preview</compilerArgs>
<compilerArgs>-Xlint:all</compilerArgs>