Class Serial

java.lang.Object
dev.gmitch215.bytebox.io.Serial

public final class Serial extends Object
Reads and writes objects in Java's own serialization format.

The bytes are the ones a JVM writes. A stream from here is readable by ObjectInputStream and a stream from ObjectOutputStream is readable here, which is what makes this usable for talking to something that already speaks the format rather than only for talking to itself.

 @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);

Compare JSON, which is the right choice when both ends are yours: JSON is smaller to read, and nothing about it has to agree with a JVM.

Since:
1.0.0
  • Method Details

    • register

      public static <T> void register(Class<T> type, SerialCodec<T> codec)
      Registers a codec.

      Called from the generated registration class during module evaluation. Registering the same type twice replaces the earlier codec, so a hand-written one can override a generated one.

      Type Parameters:
      T - the type
      Parameters:
      type - the type
      codec - the codec
    • handles

      public static boolean handles(Class<?> type)
      Whether a type can be read and written.
      Parameters:
      type - the type
      Returns:
      whether it has a codec
    • encode

      public static byte[] encode(Object value)
      Writes an object.
      Parameters:
      value - the object
      Returns:
      the stream
      Throws:
      SerialException - if the object, or anything it holds, has no codec
    • decode

      public static <T> T decode(byte[] bytes, Class<T> type)
      Reads an object.
      Type Parameters:
      T - the type
      Parameters:
      bytes - the stream
      type - what to read
      Returns:
      the object
      Throws:
      SerialException - if the stream is malformed, holds a type with no codec, or names a serialVersionUID this build does not agree with