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. Classes matching a small blocklist of known deserialization gadgets are rejected even when allow-listed. 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