Java - implement serializable [duplicate]

1

What benefits does the system have in implementing this interface in some java class? What changes in having a class that implements in comparison to one that does not have the implementation, being based 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 starting a class that is not implemented, avoiding the approach of using serializable, using code samples.

    
asked by anonymous 09.06.2016 / 16:16

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 to the file system with some extension (as shown). It can be "deserealized" in an object in the future. I would say "port" an object and its state to whatever you want.

One case that I used quite a bit was: Before Android even existed, J2ME systems implemented an object type of settings that needed to be written and read. Instead of persisting in the bank, give select, insert etc. simply the object was read, changed some configuration and persisted in a file in a directory. These preferences were sent over the web (serialized object) and in the web system had the same preferences. The point is interoperability. In some cases this is the real benefit.

Here is an example of 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 have helped.

    
09.06.2016 / 16:28