Externalizable Custom Wire Format
Take over serialization with Externalizable, writing only the fields you choose in writeExternal and restoring them in readExternal.
Code
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class Main {
public static class Point implements Externalizable {
private int x;
private int y;
// Externalizable needs a public no-argument constructor
public Point() {
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(x);
out.writeInt(y);
}
@Override
public void readExternal(ObjectInput in) throws IOException {
x = in.readInt();
y = in.readInt();
}
@Override
public String toString() {
return "Point(" + x + ", " + y + ")";
}
}
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(new Point(3, 4));
}
System.out.println("serialized bytes: " + bytes.size());
try (ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bytes.toByteArray()))) {
System.out.println("restored: " + in.readObject());
}
}
}How it works
Externalizable Custom Wire Format comes down to the classes Main and Point and the functions Point and toString.
Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Points of care
- Runs with what the toolchain already gives you — nothing extra.
Putting it to use
The primary signature is public Point()
Look for the serialized bytes:, restored: prefixes when the file runs; they tie each line to its step.
The demo flow inside main is Point — run the file to see it end to end.
Core lines
return "Point(" + x + ", " + y + ")";
Interactive Tools for This Topic
FAQ
- What does Externalizable Custom Wire Format print when run?
- No setup needed: run the file and look for labeled lines like `serialized bytes:`, `restored:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.