How to make a class serializable?

If you adopt a unit-testing methodology, then any serializable class should pass the following three tests: If it implements readObject( ) , it should implement writeObject( ) , and vice-versa. It is equal (using the equals( ) method) to a serialized copy of itself.

Bulkmailstack
 
package serializationTest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io_ObjectInputStream;
import java.io_ObjectOutputStream;
import java.util.Calendar;
import java.util.Date;
public class TestUserDetails {
public static void main(String[] args) {
// Create new UserDetails object
UserDetails myDetails = new UserDetails("Lokesh", "Gupta", 102825,
new Date(Calendar.getInstance().getTimeInMillis()));

// Serialization code
try {
FileOutputStream fileOut = new FileOutputStream("userDetails.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(myDetails);
out.close();
fileOut.close();
} catch (IOException i) {
i.printStackTrace();
}

// De-serialization code
@SuppressWarnings("unused")
UserDetails deserializedUserDetails = null;
try {
FileInputStream fileIn = new FileInputStream("userDetails.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
deserializedUserDetails = (UserDetails) in.readObject();
in.close();
fileIn.close();

// verify the object state
System.out.println(deserializedUserDetails.getFirstName());
System.out.println(deserializedUserDetails.getLastName());
System.out.println(deserializedUserDetails.getAccountNumber());
System.out.println(deserializedUserDetails.getDateOpened());
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}
}
Output:

Lokesh
Gupta
102825
Wed Nov 21 15:06:34 GMT+05:30 2012


Rentalproxies
 
Back
Top