Java - implement serializable

Asked

Viewed 921 times

1

What are the benefits for the system in implementing this interface in some java class? What changes having a class that implements compared to one that does not have the implementation, based on the fact that they have the same attributes? And what are their real uses?

Edit

My question is related to the benefits of using this interface against the start of a class that does not implement, by evading the approach of how to use serializable, using code examples.

1 answer

2


Serialization is the conversion of an object into a series of bytes. This object can be easily saved, persisted in a database for example or transmitted from one system to another over the network, or even saved in the file system with some extension (as the example). It may in the future be "undefeated" in an object. I would say "bear" an object and its state to whatever.

One case I used a lot was: Even before Android existed, on J2ME systems it implemented a type of settings object that needed to be written and read. Instead of persisting in the database, give select, Insert etc. simply the object was read, changed some configuration and persisted in a file in a directory. These preferences were sent by the web (serialized object) and on the web system they had the same preferences. The point is interoperability. In some cases this is the real benefit.

Here is an example referring to this post.

import java.io.*;
import java.util.*;

// This class implements "Serializable" to let the system know
// it's ok to do it. You as programmer are aware of that.
public class SerializationSample implements Serializable {

    // These attributes conform the "value" of the object.

    // These two will be serialized;
    private String aString = "The value of that string";
    private int    someInteger = 0;

    // But this won't since it is marked as transient.
    private transient List<File> unInterestingLongLongList;

    // Main method to test.
    public static void main( String [] args ) throws IOException  { 

        // Create a sample object, that contains the default values.
        SerializationSample instance = new SerializationSample();

        // The "ObjectOutputStream" class have the default 
        // definition to serialize an object.
        ObjectOutputStream oos = new ObjectOutputStream( 
                               // By using "FileOutputStream" we will 
                               // Write it to a File in the file system
                               // It could have been a Socket to another 
                               // machine, a database, an in memory array, etc.
                               new FileOutputStream(new File("o.ser")));

        // do the magic  
        oos.writeObject( instance );
        // close the writing.
        oos.close();
    }
}

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.