...
| Code Block | ||
|---|---|---|
| ||
String filename = "serial";
ObjectOutputStream oos = null;
try {
// Serializing using writeUnshared
oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeUnshared(jane);
} catch (Exception e) {
System.out.println("Exception during serialization" + e);
} finally {
try {
oos.close();
} catch (IOException e) {
System.out.println("Exception during serialization" + e);
}
}
// Deserializing using readUnshared
ObjectInputStream ois= null;
try {
ois = new ObjectInputStream(new FileInputStream(filename));
Professor jane2 = (Professor)ois.readUnshared();
System.out.println("checkTutees returns: " +
jane2.checkTutees());
// Prints "checkTutees returns: false"
} catch (Exception e) {
System.out.println("Exception during deserialization" + e);
} finally {
try {
ois.close();
} catch (IOException e) {
System.out.println("Exception during deserialization" + e);
}
} |
...
This compliant solution overcomes the problem of the noncompliant code example by using writeObject() and readObject(), ensuring that the tutor object referred to by the three students has a one-to-one mapping with the original Professor object. So the checkTutees() method correctly returns true.
| Code Block | ||
|---|---|---|
| ||
String filename = "serial";
ObjectOutputStream oos = null;
try {
// Serializing using writeUnshared
oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject(jane);
} catch (Exception e) {
System.out.println("Exception during serialization" + e);
} finally {
try {
oos.close();
} catch (IOException e) {
System.out.println("Exception during serialization" + e);
}
}
// Deserializing using readUnshared
ObjectInputStream ois= null;
try {
ois = new ObjectInputStream(new FileInputStream(filename));
Professor jane2 = (Professor)ois.readObject();
System.out.println("checkTutees returns: " +
jane2.checkTutees());
// Prints "checkTutees returns: false"
} catch (Exception e) {
System.out.println("Exception during deserialization" + e);
} finally {
try {
ois.close();
} catch (IOException e) {
System.out.println("Exception during deserialization" + e);
}
} |
...