Setting a Custom Filter for an Individual Stream

You can set a filter on an individual ObjectInputStream when the input to the stream is untrusted and the filter has a limited set of classes or constraints to enforce. For example, you could ensure that a stream only contains numbers, strings, and other application-specified types.

A custom filter is set using the setObjectInputFilter​ method. The custom filter must be set before objects are read from the stream.

In the following example, the setObjectInputFilter method is invoked with the dateTimeFilter method. This filter only accepts classes from the java.time package. The dateTimeFilter method is defined in a code sample in Setting a Custom Filter as a Method.

    LocalDateTime readDateTime(InputStream is) throws IOException {
        try (ObjectInputStream ois = new ObjectInputStream(is)) {
            ois.setObjectInputFilter(FilterClass::dateTimeFilter);
            return (LocalDateTime) ois.readObject();
        } catch (ClassNotFoundException ex) {
            IOException ioe = new StreamCorruptedException("class missing");
            ioe.initCause(ex);
            throw ioe;
        }
    }