Friday, February 12, 2021

Sealed classes and reflection

Two new methods are added to java.lang.Class to examine if a Class or an Interface is a sealed class and if so, to find what are its supported subtypes. 

These two methods are 

1. isSealed - which returns a boolean indicating if the class is sealed or  not

2. permittedSubclasses- which returns an array of ClassDesc representing the supported sub classes

Below sample code demonstrates this

import java.lang.constant.ClassDesc;

public sealed interface Pet {
    
}

final class Cat implements Pet {

}

final class Dog implements Pet {
    
}

class Main {
    public static void main(String[] args) {
        System.out.println("Pet is a sealed class: "+Pet.class.isSealed());
        System.out.print("Its supported subtypes are: ");
        ClassDesc[] cDescArr = Pet.class.permittedSubclasses();
        for (ClassDesc cDesc : cDescArr) {
            System.out.print(cDesc.displayName()+" ");
        }
    }
}

The output of the above program is

Pet is a sealed class: true
Its supported subtypes are: Cat Dog

We will move on to the another new feature in Java 15 - Records in the next post

Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/02/Language-Features/Sealed-classes/Reflection

No comments:

Post a Comment