Java Reference
In-Depth Information
System.err.println("i/o
error:
"+ioe.getMessage());
return;
}
try (ObjectInputStream ois =
new
ObjectInputStream(new
FileIn-
putStream(FILENAME)))
{
Employee emp = (Employee) ois.readObject();
System.out.println(emp.getName());
System.out.println(emp.getAge());
}
catch (ClassNotFoundException cnfe)
{
System.err.println(cnfe.getMessage());
}
catch (IOException ioe)
{
System.err.println(ioe.getMessage());
}
}
}
Listing 8-15 ' s main() method first instantiates Employee and serializes this in-
stance via writeObject() to employee.dat . It then deserializes this instance
from this file via readObject() and invokes the instance's getName() and
getAge() methods.Alongwith employee.dat ,you'lldiscoverthefollowingout-
put when you run this application:
John Doe
36
There's no guarantee that the same class will exist when a serialized object is
deserialized (perhaps an instance field has been deleted). During deserialization, this
mechanism causes readObject() to throw an instance of
java.io.InvalidClassException (an indirect subclass of IOException )
when it detects a difference between the deserialized object and its class.
Search WWH ::




Custom Search