Java ValidatingObjectInputStream-class And Method Code Example


Here is an example of how to use the ValidatingObjectInputStream class from the Apache Commons IO library in Java:

import org.apache.commons.io.input.ValidatingObjectInputStream;
import java.io.*;

public class Example {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        try (FileInputStream fis = new FileInputStream("data.bin");
             ObjectInputStream ois = new ValidatingObjectInputStream(fis)) {
            ois.accept(new MyValidator());
            Object obj = ois.readObject();
            System.out.println("Read object: " + obj);
        }
    }
}

class MyValidator implements ValidatingObjectInputStream.ValidationCallback {
    @Override
    public void validateObject(Object obj) throws InvalidObjectException {
        if (!(obj instanceof MyClass)) {
            throw new InvalidObjectException("Not a MyClass object");
        }
    }
}

class MyClass implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    // constructor, getters and setters here
}

This example demonstrates how to use the ValidatingObjectInputStream class to validate the objects being read from a binary file. It creates a ValidatingObjectInputStream wrapping a FileInputStream which reads from a file "data.bin". Then it sets the validation callback by calling accept method with an instance of MyValidator class. Then it reads an object from the stream and print it.

The MyValidator class implements the ValidationCallback interface, which requires the implementer to provide a validateObject method that checks whether the object is valid or not. In this case, the method checks if the object is an instance of MyClass and if not, it throws an InvalidObjectException.

Please note that this class is not thread-safe and it's a simple way to validate the class of deserialized object.