6. Additionalincompabilitiyexample
No. #now() returnsnanosecondspartbyJDK-8068730(Java9)
# Version 14.0.2
jshell> var now = java.time.LocalDateTime.now()
now ==> 2020-10-08T16:19:01.738366
# Version 15
jshell> var now = java.time.LocalDateTime.now()
now ==> 2020-10-08T16:19:08.485590579
jshell> var now = java.time.LocalDateTime.now()
...> .truncatedTo(java.time.temporal.ChronoUnit.MICROS)
now ==> 2020-10-08T16:19:12.943847
6
7. Additionalincompabilitiyexample(Cont.)
#now() returnsnanosecondspartbyJDK-8068730(Java9)
# Version 15, Linux
jshell> var now = java.time.LocalDateTime.now()
now ==> 2020-10-08T16:30:29.534948147
jshell> System.getProperty("os.name")
$2 ==> "Linux"
# Version 15, macOS
jshell> var now = java.time.LocalDateTime.now()
now ==> 2020-10-08T16:31:26.815258
jshell> System.getProperty("os.name")
$2 ==> "Mac OS X"
Windowsはもっと前(環境がないので未確認)
7
12. (Drafting)thesamewayon switch
別JEPでswitch⽂でも利⽤できるようになる予定です。ただし時期未詳
switch (obj) {
case Integer i:
// uses i here.
case Double d:
// uses d here.
}
public double area(Shape shape) {
return switch(shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.length() * r.width();
case Square s -> s.length() * s.width();
default -> 0;
}
}
12
15. 15:384:Records(SecondPreview)(Cont.)
//⼀番シンプルな書き⽅
public record TestRecord(String s, int i) {}
public final class TestRecord(String s, int i)
extends java.lang.Record {
private final String s;
private final int i;
String s() { return s; }
int i() {return i;}
TestRecord(String s, int i) {
this.s = s;
this.i = i;
}
// toString(), equals(), hashCode()
}
15
16. 15:384:Records(SecondPreview)(Cont.)
public final class TestRecord(String s, int i)
extends java.lang.Record {
Immutable
recordは常に final クラス
(java.lang.Recordを拡張しているので)recordはインターフェースを実装できるがクラ
スを拡張はできない
(同じ理由で)Objectクラスが持つ以下の3つのメソッドが暗黙的に実装されている
// toString(), equals(), hashCode()
equals() はrecordが持つフィールドが同値であれば常に true
16
17. 15:384:Records(SecondPreview)(Cont.)
private final String s;
private final int i;
Immutable
フィールドは private final でsetterもなし
Reflectionを使っても変更は不可
やったら IllegalAccessException が投げられる
String s() { return s; }
int i() {return i;}
FluentgetterAPI, getS や getI のように getXX は追加できない
17
18. 15:384:Records(SecondPreview)(Cont.)
// ⼀般的な⽣成されたコンストラクタ
TestRecord(String s, int i) {
this.s = s;
this.i = i;
}
下記のようにコンストラクタで検証(validate)や値の⽣成も可能
public record TestRecord(String s, int i) {
public TestRecord() {
this("Default S", 1000);
}
public TestRecord(String s, int i) {
if (s.isEmpty()) {
throw new IllegalArgumentException();
}
this.s = s;
this.i = i;
}
}
18