GradleでJava 14のプレビュー機能を試す
GradleでJava 14のプレビュー機能を試したときのメモ。
Gradleは6.3以降を使用する。
Gradle 6.3 Release Notes
IntelliJ IDEAでJava 14を使う場合は、2020.1以降を使用する。
Java 14 and IntelliJ IDEA | The IntelliJ IDEA Blog
ソースコード
build.gradle
plugins { id 'java' id 'application' } group 'com.example' version '1.0-SNAPSHOT' sourceCompatibility = JavaVersion.VERSION_14 repositories { mavenCentral() } tasks.withType(JavaCompile) { options.compilerArgs += ['--enable-preview'] } mainClassName = 'com.example.Main' run { jvmArgs = ['--enable-preview'] } test { jvmArgs = ['--enable-preview'] }
Main.java
今回はRecordsを試す
JEP 359: Records (Preview)
package com.example; public class Main { public static void main(String... args) { Point point = new Point(1, 2); System.out.println(point); Range range = new Range(1, 2); System.out.println(range); } record Point(int x, int y) {} record Range(int lo, int hi) { public Range { if (lo > hi) { throw new IllegalArgumentException("(%d,%d)".formatted(lo, hi)); } } } }
実行結果
% ./gradlew run > Task :run Point[x=1, y=2] Range[lo=1, hi=2] BUILD SUCCESSFUL in 1s