Java Reference
In-Depth Information
todiscoverthisinformationandwreakhavoc.It'sbettertogivethedevelopera
choice to prevent this from happening.
Performance :SerializationleveragestheReflectionAPI,whichIintroducedin
Chapter 4 . In that chapter, you learned that reflection slows down application
performance.Unlimitedserializationcouldreallyhurtanapplication'sperform-
ance.
Objects not amenable to serialization :Someobjectsexistonlyinthecontextof
arunningapplicationandit'smeaninglesstoserializethem.Forexample,afile
stream object that's deserialized no longer represents a connection to a file.
Listing8-14 declaresan Employee classthatimplementsthe Serializable in-
terface to tell the JVM that it's okay to serialize Employee objects.
Listing 8-14. Implementing Serializable
class Employee implements java.io.Serializable
{
private String name;
private int age;
Employee(String name, int age)
{
this.name = name;
this.age = age;
}
String getName() { return name; }
int getAge() { return age; }
}
Because Employee implements Serializable ,theserializationmechanismwill
not throw NotSerializableException when serializing an Employee object.
Notonlydoes Employee implement Serializable ,the String classalsoimple-
ments this interface.
Your second task is to work with the ObjectOutputStream class and its void
writeObject(Object obj) methodtoserializeanobject,andthe OutputIn-
putStream classandits Object readObject() methodtodeserializetheobject.
Note Although ObjectOutputStream extends OutputStream instead of
FilterOutputStream , and although ObjectInputStream extends In-
 
Search WWH ::




Custom Search