...
This noncompliant code example attempts to serialize the data from the previous example using writeUnshared()
. 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.
Code Block | ||
---|---|---|
| ||
String filename = "serial"; try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) { // Serializing using writeUnshared oos.writeUnshared(jane); } catch (ExceptionThrowable 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 (ExceptionThrowable 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 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. The checkTutees()
method correctly returns true
.
Code Block | ||
---|---|---|
| ||
String filename = "serial"; try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) { // Serializing using writeUnshared oos.writeObject(jane); } catch (ExceptionThrowable e) { // Handle error } // Deserializing using readUnshared try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) { Professor jane2 = (Professor)ois.readObject(); System.out.println("checkTutees returns: " + jane2.checkTutees()); } catch (ExceptionThrowable e) { // Handle error } |
Applicability
...