JDK

Java 17 新機能(2)

JEP 406: switch文でのパターンマッチング (プレビュー)

switch文が更に拡張されている。caseラベルにクラス名を指定することで,インスタンスの型に応じて条件分岐できるようになりました。次の例ではObject型,Parent型,ChildA型のオブジェクトとnullを渡して,条件分岐させています。

コンパイルには,–enable-previewオプションと –source 17オプションをつける必要があります。

public class Switch01
{
    public static void main(final String[] args)
    {
        Object[] array = new Object[]{ new Object(), new Parent(), new ChildA(), null };
        for(Object obj : array)
        {
            switch(obj)
            {
                case null:
                    System.out.println("null");
                    break;
                case ChildA c:
                    System.out.println("ChildA class");
                    break;
                case Parent p:
                    System.out.println("Parent class");
                    break;
                default:
                    System.out.println("Other class");
            }
        }
    }
}
class Parent{}
class ChildA extends Parent{}

Other class
Parent class
ChildA class
null

更には,switchラベルに続けてboolean型の条件を続けることができるよう拡張されました。次の例ではshape変数に格納されているオブジェクトがCircleクラスの場合で,かつ,getArea()の戻り値が100を超えている場合にLarge Circleというメッセージを表示します。

public class Switch02
{
    public static void main(final String[] args)
    {
        Shape[] array = new Shape[] { null, new Circle(1), new Circle(10), new Rectangle(5, 3) };
        for(Shape shape : array)
        {
            switch(shape)
            {
                case null ->
                    System.out.println("null");
                case Circle c && c.getArea() > 100 ->
                    System.out.println("Large Circle");
                case Rectangle r ->
                    System.out.println("Rectangle");
                default ->
                    System.out.println("other");
            }
        }
    }
}
/** 図形 */
abstract class Shape
{
    /** 
     面積を返す
     * @return 面積
    */
    abstract double getArea();
}
/** 円 */
class Circle extends Shape
{
    /** 半径 */
    private double radius;
    public Circle(final double radius)
    {
        this.radius = radius;
    }
    public double getArea()
    {
        return Math.PI * Math.pow(radius,2);
    }
}
/** 矩形 */
class Rectangle extends Shape
{
    /** 幅 */
    private double width;
    /** 高さ */
    private double height;
    public Rectangle(final double width, final double height)
    {
        this.width = width;
        this.height = height;
    }
    public double getArea()
    {
        return width * height;
    }
}

null
other
Large Circle
Rectangle