How to obtain instances of all subclasses of sealed class?

1000 Views Asked by At

Is there a way to get a collection of instances of subclasses, which are permitted in sealed class?

It would be nice to have something similar to Enum.values() method, because I don't want to collect them manually.

The best I could do is:

abstract sealed class Color permits Green, Red /*, ...*/ {

  Iterable<Color> values() {
    return Arrays.stream((Class<Color>[]) Color.class.getPermittedSubclasses())
        .flatMap(subclass -> {
          try {
            return Stream.of(subclass.getDeclaredConstructor().newInstance());
          } catch (ReflectiveOperationException ignore) {
            return Stream.empty();
          }
        }).toList();
  }
}
0

There are 0 best solutions below