Getting info about saled classes (using reflection) – Sealed and Hidden Classes
174. Getting info about saled 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: “
+ Inspector.permittedClasses(Fuel.class));
// [class com.refinery.fuel.Coke,
// class com.refinery.fuel.Charcoal]
System.out.println(“SolidFuel subclasses: “
+ Inspector.permittedClasses(SolidFuel.class));
// []
System.out.println(“Coke subclasses: “
+ Inspector.permittedClasses(coke.getClass()));
// [class com.refinery.fuel.Chloromethane,
// class com.refinery.fuel.Dichloromethane]
System.out.println(“Methane subclasses: “
+ Inspector.permittedClasses(methane.getClass()));
I think you got the idea!
175. Listing top 3 Sealed Classes’ benefits
Maybe you have your own top 3 Sealed Classes’ benefits that don’t match the following list. That’s ok, no problem, they are benefits after all Sealed Classes sustain better design and clearly expose their intentions: Before using Sealed Classes, we have to rely only on the final keyword (which is expressive enough), and package-private classes/constructors. Obviously, package-private code needs some reading between the lines to understand its intention since is not easy to spot a closed hierarchy modeled via this hack. On the other hand, Sealed Classes expose their intentions very clear and expressive.The compiler can rely on sealed classes to perform finer checks on our behalf: Nobody can sneak a class in a hierarchy closed via Sealed Classes. Any such attempt is rejected via a clear and meaningful message. The compiler is guarding for us and acts as the first line of defense against any accidental/non-accidental attempt to use our closes hierarchies in an improper way.Sealed Classes help the compiler to provide better pattern matching: You’ve experimented with this benefit in Problem 172. The compiler can rely on Sealed Classes to determine if a switch has covering all the possible input values and therefore is exhaustive. And, this is just the beginning of what Sealed Classes can do for pattern matching.