Java Reference
In-Depth Information
The method
checkTutees()
checks whether all of the tutees of this professor have this
professor as their tutor, returning
true
if that is the case and
false
otherwise.
Suppose that Professor Jane has three students, Able, Baker, and Charlie, all of whom
have Professor Jane as their tutor. Issues can arise if the
writeUnshared()
and
readUn-
shared()
methods are usedwith these classes, asdemonstrated inthe following noncom-
pliant code example.
Noncompliant Code Example
This noncompliant code example attempts to serialize data using
writeUnshared()
.
String filename = "serial";
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(filename))) {
// Serializing using writeUnshared
oos.writeUnshared(jane);
} catch (Throwable e) {
// Handle error
}
// Deserializing using readUnshared
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream(filename))){
Professor jane2 = (Professor)ois.readUnshared();
System.out.println("checkTutees returns: " +
jane2.checkTutees());
} catch (Throwable e) {
// Handle error
}
However, when the data is deserialized using
readUnshared()
, the
checkTutees()
method no longer returns
true
because the tutor objects of the three students are different
from the original
Professor
object.
Compliant Solution
This compliant solution uses the
writeObject()
and
readObject()
methods to ensure
that the tutor object referred to by the three students has a one-to-one mapping with the
original
Professor
object. The
checkTutees()
method correctly returns
true
.