Search code examples
javaserializationkryo

Kryo Serialization Type Detection


I'm using Kryo IO directly to do my own low level primitive serialization of Strings, Longs and Doubles.

What I'm wondering is if there is any way for Kryo IO to automatically detect the primitive data types from the serialized bytes when reading them back?

If I have a byte array of say 10 serialized values, and I don't know if they were Strings, Longs, or Doubles; is there any way for Kryo to determine the data types (like MsgPack can)?


Solution

  • Kryo is no different to the normal Java serialization in this respect. There are two ways in which the deserializer can know what type it is deserializing each time:

    1. It is a field in a known class, so the deserializer implementation reads each field in its proper order.

    2. There is type information embedded in the stream in some manner to let it know. The writeClassAndObject() method in Kryo does just that - it prepends a compact class identifier to the actual object content, letting the deserializer know what to do.

      Alternatively, you can do something like this manually e.g. by sending a single byte that would select among a limited number of supported types.

    Besides, this is what the MessagePack format mandates as well...