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.

public class NetworkWindow extends Frame implements Serializable {<br />

}<br />

private Socket theSocket;<br />

// several dozen other fields and methods<br />

You could make this class fully serializable by merely declaring theSocket transient:<br />

private transient Socket theSocket;<br />

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

Let's assume you actually do want to restore the state of the socket when the object is<br />

deserialized. In this case, you can use private readObject() and writeObject() methods as<br />

in the last section. You can use defaultReadObject() and defaultWriteObject() methods<br />

to handle all the normal, nontransient fields; then handle the socket specifically. For example:<br />

private void writeObject(ObjectOutputStream out) throws <strong>IO</strong>Exception {<br />

}<br />

out.defaultWriteObject();<br />

out.writeObject(theSocket.getInetAddress());<br />

out.writeInt(theSocket.getPort());<br />

private void readObject(ObjectInputStream in)<br />

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

}<br />

in.defaultReadObject();<br />

InetAddress ia = (InetAddress) in.readObject();<br />

int thePort = in.readInt();<br />

this.theSocket = new Socket(ia, thePort);<br />

It isn't even necessary to know what the other fields are to make this work. The only extra<br />

work that has to be done is for the transient fields. This technique applies far beyond this one<br />

example. It can be used anytime when you're happy with the default behavior and merely<br />

want to do additional things on serialization or deserialization. For instance, it can be used to<br />

set the values of static fields or to execute additional code when deserialization is complete.<br />

However, if the latter is your intent, you might be better served by validation, discussed later<br />

in the chapter. For example, let's suppose you have a Die class that must have a value<br />

between 1 and 6, as shown in Example 11.4.<br />

Example 11.4. A Six-Sided Die<br />

import java.util.*;<br />

import java.io.*;<br />

public class Die implements Serializable {<br />

private int face = 1;<br />

Random shooter = new Random();<br />

public Die(int face) {<br />

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

}<br />

255

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

Saved successfully!

Ooh no, something went wrong!