Annotation Interface SerialType


@Retention(RUNTIME) @Target(TYPE) public @interface SerialType
Generates a codec that reads and writes this type in Java's own serialization format.

The bytes are the ones a JVM writes, so a stream produced here is readable by ObjectInputStream and a stream from ObjectOutputStream is readable here. The type must implement Serializable, because the format encodes that it does.

 @SerialType
 public record Order(String sku, int quantity, long total) implements Serializable {}

 byte[] wire = Serial.encode(new Order("abc", 2, 9_007_199_254_740_993L));
 Order back = Serial.decode(wire, Order.class);

Generated rather than reflective for the same reason the JSON codecs are: a reflective implementation has to keep field metadata for every class that could arrive through an Object-typed field, which is the whole-program closure dead-code elimination exists to prune. A codec per named type keeps the closure to what was asked for.

What the generator refuses, it refuses at build time and says why:

  • a custom writeObject, readObject, writeReplace or readResolve
  • Externalizable
  • a class library collection as a field type, because its format is its own private writeObject rather than its fields
  • a class that is neither a record nor has a no-argument constructor, because deserialization has to build the instance and there is no Unsafe on this platform to build it without
Since:
1.0.0