When working with ObjectInputStream and ObjectOutputStream in Java, developers often encounter some common pitfalls. These mistakes can lead to issues such as ClassNotFoundException, serialization problems, or inefficient data handling.
Serializable
interface in the class of objects being serialized.serialVersionUID
can lead to InvalidClassException
when deserializing objects that have changed over time.transient
keyword works; transient fields will not be serialized, which can cause loss of important data.
import java.io.*;
// Sample class that implements Serializable
class Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
transient String password; // This field will not be serialized
Person(String name, int age, String password) {
this.name = name;
this.age = age;
this.password = password;
}
}
public class SerializeDemo {
public static void main(String[] args) {
Person person = new Person("John Doe", 30, "secretPassword");
// Serialization
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
out.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
// Deserialization
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) {
Person deserializedPerson = (Person) in.readObject();
System.out.println("Deserialized Person: " + deserializedPerson.name + ", " + deserializedPerson.age);
// Password will be null due to transient
System.out.println("Password: " + deserializedPerson.password);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?