Browse DevX
Sign up for e-mail newsletters from DevX


Implement Persistent Objects with Java Serialization : Page 3

One of the most critical operations an application can perform is saving and restoring its state between successive runs. Yet, saving data in a textual format is not always practical--or secure. Using serialization, you can save any Java object to disk in a flash.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Restoring Objects from a Serialized State
Once you have saved your data type to a file, you have to be able to read it back in again. Reading objects back is almost as easy as writing them. The one catch is that at runtime the Java runtime engine can never be completely sure what type of data to expect. After all, a data stream containing serialized objects may well contain a mixture of different object classes.

So Java simply will read data back as generic java.lang.Object types. You need to explicitly cast this generic object to a particular class, a relatively straightforward procedure. You simply tell Java to interpret a specific set of data as an instance of a specific data type or class. You can do this by first checking the object's class, using the instance of operator, and then casting to the correct class, like so:

// Read from disk using FileInputStream. FileInputStream f_in = new FileInputStream ("myobject.data"); // Read object using ObjectInputStream. ObjectInputStream obj_in = new ObjectInputStream (f_in); // Read an object. Object obj = obj_in.readObject (); // Is the object that you read in, say, an instance // of the Vector class? if (obj instanceof Vector) { // Cast object to a Vector Vector vec = (Vector) obj; // Do something with vector ... } else // ... the object is some other type ...

Further Issues with Serialization
As you can see, it's relatively easy to serialize an object. Whenever new fields are added to an object, they will be saved automatically without requiring modification to your save and restore code.

However, this behavior is not desirable in all cases. For example, transmitting a password member variable to third parties over a network connection might not be safe. You might need to leave it blank. In this case, you can use a special keyword ("transient"). The transient field indicates that a particular member variable should not be saved. Though not used often, it's an important keyword to remember. Use it like so:

public class UserSession implements java.io.Serializable { String username; transient String password; }

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date