The interface java.io.Serializable is just a marker, doesn't have any methods to implement. It tells the Jvm that a particular class is serializable.
The dependencies need to implement Serializable to be serialized or an exception is generated.
Superclasses fields are serialized only if the superclass implements Serializable, else they are ignored.
Static and transient fields are ignored.
A static field serialVersionUID must be provided. It is used to check if deserialized object and receiver are of the same type.
Here's a serialization example:
package org.davis.serialization; import java.io.Serializable; public class Customer implements Serializable { private final static long serialVersionUID = 1L; private String name; private int id; public Customer(String name, int id) { this.name = name; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } } package org.davis.serialization; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializationTest { public static void main(String[] args) throws FileNotFoundException { Customer custToSerialize = new Customer("Martin",1); // Serialize the customer object try(ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("serialized.txt"))) { oos.writeObject(custToSerialize); } catch (IOException e) { System.err.println("An I/O error occurred"); System.exit(-1); } // Deserialize the customer object try (ObjectInputStream ois = new ObjectInputStream( new FileInputStream("serialized.txt"))) { Customer custDeserialized = (Customer)ois.readObject(); if (custDeserialized != null && custToSerialize.getName().equals("Martin")) { // Deserialization succesfull System.out.println("Object succesfully deserialized!"); } } catch (IOException e) { System.err.println("An I/O error occurred"); System.exit(-1); } catch (ClassNotFoundException e) { System.err.println("Class not recognized"); System.exit(-1); } } }
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.