toObjectSecure
Deserialize with type validation and security checks.
Every class in the stream, including superclasses (e.g. Number for an Integer), must be in allowedClasses, and each class name is checked before the class is loaded. Classes matching a small blocklist of known deserialization gadgets, and arrays of them, are rejected even when allow-listed. A dynamic proxy is read only when java.lang.reflect.Proxy, its invocation handler's class and every interface it implements are allowed, and none of them is blocklisted.
Strings are read without a class check, so a String nested in an allowed object (a field, or an element of an allowed array or collection) needs no allow-list entry. The top-level object is checked, though: reading a String, a Class or an ObjectStreamClass as the result requires that class in allowedClasses.
The stream is also bounded by a JEP 290 ObjectInputFilter: object graphs may nest at most MAX_DEPTH levels, and no array may declare more elements, nor the stream hold more object references, than the payload has bytes. Every element and reference costs at least one byte of input, so these bounds reject nothing a genuine stream contains, while stopping a tiny payload from declaring a huge array and forcing its allocation before a single element is read.
Hash-based collections (HashSet, HashMap, java.util.Hashtable) are risky to allow-list for untrusted input: nested sets whose hash codes must be recomputed at every level cost time exponential in the depth. The depth limit keeps that bounded, but prefer lists and arrays where you can.
Parameters
The expected class type for validation
Classes allowed for deserialization (security whitelist); must not be empty
Throws
if allowedClasses is empty
if the payload is too large, or a class is blocklisted or not in allowedClasses
if the stream exceeds the depth, array-length or reference limits
if the object cannot be cast to the expected type, including a serialized null