136. Implementing a custom class ObjectInputFilter
Let’s assume that we already have the Melon
class and the helper methods for serializing/deserializing objects to/from byte arrays from Problem 131.
An ObjectInputFilter
can be written via a dedicated class by implementing the ObjectInputFilter
functional interface as in the following example:
public final class MelonFilter implements ObjectInputFilter {
@Override
public Status checkInput(FilterInfo filterInfo) {
Class<?> clazz = filterInfo.serialClass();
if (clazz != null) {
// or, clazz.getName().equals("modern.challenge.Melon")
return
!(clazz.getPackage().getName().equals("modern.challenge")
&& clazz.getSimpleName().equals("Melon"))
? Status.ALLOWED : Status.REJECTED;
}
return Status.UNDECIDED;
}
}
This filter is exactly the same as the pattern-based filter, !modern.challenge.Melon
, only that it is expressed via Java Reflection.
We can...