181. Getting info about sealed classes (using reflection)
We can inspect sealed classes via two methods added as part of the Java Reflection API. First, we have isSealed(), which is a flag method useful to check if a class is or isn’t sealed. Second, we have getPermittedSubclasses(), which returns an array containing the permitted classes. Based on these two methods, we can write the following helper to return the permitted classes of a sealed class:
public static List<Class> permittedClasses(Class clazz) {
if (clazz != null && clazz.isSealed()) {
return Arrays.asList(clazz.getPermittedSubclasses());
}
return Collections.emptyList();
}
We can easily test our helper via the Fuel model as follows:
Coke coke = new Coke();
Methane methane = new Methane();
// [interface com.refinery.fuel.SolidFuel,
// interface com.refinery.fuel.LiquidFuel,
// interface com.refinery.fuel.GaseousFuel]
System.out.println("Fuel subclasses: "...