Setting a Custom Filter as a Class
A custom filter can be implemented as a class implementing the java.io.ObjectInputFilter interface, as a lambda expression, or as a method.
A filter is typically stateless and performs checks solely on the input
parameters. However, you may implement a filter that, for example, maintains state
between calls to the checkInput
method to count artifacts in the
stream.
In the following example, the FilterNumber
class allows any
object that is an instance of the Number
class and rejects all
others.
class FilterNumber implements ObjectInputFilter {
public Status checkInput(FilterInfo filterInfo) {
Class<?> clazz = filterInfo.serialClass();
if (clazz != null) {
return (Number.class.isAssignableFrom(clazz))
? ObjectInputFilter.Status.ALLOWED
: ObjectInputFilter.Status.REJECTED;
}
return ObjectInputFilter.Status.UNDECIDED;
}
}
In the example:
- The
checkInput
method accepts anObjectInputFilter.FilterInfo
object. The object’s methods provide access to the class to be checked, array size, current depth, number of references to existing objects, and stream size read so far. - If
serialClass
is not null, then the value is checked to see if the class of the object isNumber
. If so, it is accepted and returnsObjectInputFilter.Status.ALLOWED
. Otherwise, it is rejected and returnsObjectInputFilter.Status.REJECTED
. - Any other combination of arguments returns
ObjectInputFilter.Status.UNDECIDED
. Deserialization continues, and any remaining filters are run until the object is accepted or rejected. If there are no other filters, the object is accepted.