Package dev.gmitch215.bytebox.io
Class Serial
java.lang.Object
dev.gmitch215.bytebox.io.Serial
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 Summary
Modifier and TypeMethodDescriptionstatic <T> TReads an object.static byte[]Writes an object.static booleanWhether a type can be read and written.static <T> voidregister(Class<T> type, SerialCodec<T> codec) Registers a codec.
-
Method Details
-
register
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 typecodec- the codec
-
handles
Whether a type can be read and written.- Parameters:
type- the type- Returns:
- whether it has a codec
-
encode
Writes an object.- Parameters:
value- the object- Returns:
- the stream
- Throws:
SerialException- if the object, or anything it holds, has no codec
-
decode
Reads an object.- Type Parameters:
T- the type- Parameters:
bytes- the streamtype- what to read- Returns:
- the object
- Throws:
SerialException- if the stream is malformed, holds a type with no codec, or names aserialVersionUIDthis build does not agree with
-