Testing code that uses the Serializable interface in Java requires a few key steps. The general approach involves creating instances of your serializable classes, serializing them into a byte stream, and then deserializing them back into objects to ensure that their states are preserved and that all properties are correctly restored.
Here is a simple example demonstrating how to test a Serializable class in Java:
public class Example implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Example(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters
public static void main(String[] args) {
Example original = new Example("John Doe", 30);
// Serialize
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(original);
out.flush();
// Deserialize
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
Example deserialized = (Example) in.readObject();
// Verify
System.out.println(original.getName().equals(deserialized.getName())); // true
System.out.println(original.getAge() == deserialized.getAge()); // true
}
}
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?