23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

public int getFace() {<br />

return this.face;<br />

}<br />

public void setFace(int face) {<br />

this.face = (int) (Math.abs(face % 6) + 1);<br />

}<br />

public int roll() {<br />

this.face = (int) ((Math.abs(shooter.nextInt()) % 6) + 1);<br />

return this.face;<br />

}<br />

public static void main(String[] args) {<br />

}<br />

Die d = new Die(2);<br />

for (int i = 0; i < 10; i++) {<br />

d.roll();<br />

System.out.println(d.getFace());<br />

}<br />

<strong>Java</strong> I/O<br />

Obviously, this class, simple as it is, goes to a lot of trouble to ensure that the die always has a<br />

value between 1 and 6. Every method that can possibly set the value of the private field face<br />

carefully checks to make sure the value is between 1 and 6. However, serialization provides a<br />

back door through which the value of face can be changed, because default serialization uses<br />

neither constructors nor set methods but accesses the private field directly. To close the door,<br />

you can provide a readObject() method that performs the necessary check:<br />

private void readObject(ObjectInputStream in)<br />

throws <strong>IO</strong>Exception, ClassNotFoundException {<br />

}<br />

in.defaultReadObject();<br />

this.face = (int) (Math.abs(this.face % 6) + 1);<br />

In this example, the normal serialization format is perfectly acceptable, so that's completely<br />

handled by defaultReadObject(). It's just that a little more work is required than merely<br />

restoring the fields of the object.<br />

11.8.3 Preventing Serialization<br />

On occasion, you need to prevent a normally serializable subclass from being serialized. This<br />

most commonly occurs with components that are serializable, because java.awt.Component<br />

is serializable. You can prevent an object from being serialized, even though it or one of its<br />

superclasses implements Serializable, by throwing a NotSerializableException from<br />

writeObject(). NotSerializableException is a subclass of<br />

java.io.ObjectStreamException, which is itself a kind of <strong>IO</strong>Exception:<br />

public class NotSerializableException extends ObjectStreamException<br />

For example:<br />

256

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!