Cả hai đều là quá trình chuyển đổi đối tượng thành byte stream để lưu trữ (file, database, network). Sự khác biệt nằm ở mức độ kiểm soát.
Bảng so sánh chi tiết
| STT | Tiêu chí | Serialization (Serializable) |
Externalization (Externalizable) |
|---|---|---|---|
| 1 | Interface | Marker interface (không có method) | Chứa 2 method: readExternal, writeExternal |
| 2 | Logic triển khai | JVM tự động xử lý qua readObject/writeObject (reflection) |
Lập trình viên tự viết logic qua override 2 method trên |
| 3 | Bỏ qua biến | Dùng từ khóa transient |
Tự viết logic bỏ qua trong writeExternal |
| 4 | Hiệu suất | Chậm hơn do dùng reflection | Nhanh hơn, kiểm soát hoàn toàn |
| 5 | Kế thừa | Subclass có thể serialize dù superclass không. Superclass serialize → subclass tự động serialize | Áp dụng tương tự, nhưng cần gọi super trong method override |
Ví dụ Externalizable
class ExternalizableExample implements Externalizable {
Integer id;
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(id); // Tự quyết định ghi gì
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.id = in.readInt(); // Tự quyết định đọc gì
}
}
Ví dụ Serializable
class SerializableExample implements Serializable {
private static final long serialVersionUID = 5081877L; // Khuyến nghị khai báo
String name;
transient String password; // Không được serialize
}
Khi nào dùng cái nào?
- Serializable: Đơn giản, ít logic tùy chỉnh, prototype nhanh.
- Externalizable: Cần hiệu suất cao, format dữ liệu đặc biệt, bảo mật (mã hóa trước khi ghi), versioning phức tạp.
Lưu ý
Externalizable extends Serializable. Khi implement Externalizable, phải cung cấp constructor không tham số (public no-arg constructor) để JVM có thể tạo instance khi deserialize.