UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Java】Java17がリリースされたのでキャッチアップ

9月にJava17がリリースされた

Java11あたりからのアップデートが滞っていたのでキャッチアップしたい

そんなとき、Java女子部イベントの資料が丁度よかったのでこちらを参考にさせてもらった

speakerdeck.com

知らなかったことだけ

JEP 361: Switch Expressions

JEP 361: Switch Expressions

Java13まで

String currency;

switch(language) {
  case JA:
    currency = "JPY";
    break;
  case KO:
    currency = "KRW";
    break;
  default:
    currency = "USD";
};

Java14から

String currency = switch(language) {
  case JA -> "JPY";
  case KO -> "KRW";
  default -> "USD";
};

:を使う場合で、値を返すときはyieldを使う

String currency = switch(language) {
  case JA:
    yield "JPY";
  case KO:
    yield "KRW";
  default:
    yield "USD";
};

JEP 378: Text Blocks

JEP 378: Text Blocks

Java14まで

String html = 
        "<html>\n" +
        "    <body>\n" +
        "        <p>Hello, world</p>\n" +
        "    </body>\n" +
        "</html>\n";

Java15から

String html = """
      <html>
          <body>
              <p>Hello, world</p>
          </body>
      </html>
      """;

formatは以下のようにして行える

String source = """
                public void print(%s object) {
                    System.out.println(Objects.toString(object));
                }
                """.formatted(type);

JEP 395: Records

JEP 395: Records

Java15まではgettersetterequalstoStringhashCodeのようなメソッドやコンストラクタを持つクラスは手書き、もしくはLombok のようなライブラリを使用する必要があった

Java16からRecordsクラスを使うとこれらが自動で作られるようになった

このように定義すると

record Point(int x, int y) { }

下のようにコンパイルされる

record Point(int x, int y) {
    // Implicitly declared fields
    private final int x;
    private final int y;

    // Other implicit declarations elided ...

    // Implicitly declared canonical constructor
    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

JEP 394: Pattern Matching for instanceof

Java15まではオブジェクトが特定の型であるかどうかを検証したあと、オブジェクトをその特定の型にキャストする必要があった

if (person instanceof Customer) {
    Customer customer = (Customer) person;
    customer.pay();
}

Java16からオブジェクトが特定の型であると判明したら、そのスコープの中ではオブジェクトが自動でその型にキャストされる

if (person instanceof Customer customer) {
    customer.pay();
}

Java17

Java 17は、Java 11以来3年ぶりの長期サポート対象となるJavaのバージョン

M1 Macのサポート、Sealed Classの追加など、以下のような機能がはいる

306: Restore Always-Strict Floating-Point Semantics
356: Enhanced Pseudo-Random Number Generators
382: New macOS Rendering Pipeline
391: macOS/AArch64 Port
398: Deprecate the Applet API for Removal
403: Strongly Encapsulate JDK Internals
406: Pattern Matching for switch (Preview)
407: Remove RMI Activation
409: Sealed Classes
410: Remove the Experimental AOT and JIT Compiler
411: Deprecate the Security Manager for Removal
412: Foreign Function & Memory API (Incubator)
414: Vector API (Second Incubator)
415: Context-Specific Deserialization Filters

https://openjdk.java.net/projects/jdk/17/

実装が変わりそうなのはSealedクラスくらいかと思うが、Sealedクラスを理解するには時間がかかりそうなので別の機会にする