Results 1 to 3 of 3

Thread: Binary Serialization in Java

  1. #1
    Join Date
    Feb 2010
    Posts
    136

    Binary Serialization in Java

    1. The basics of serialization
    The Java API provides us with the tools needed to serialize the following:

    - interface Serializable
    - Class ObjectOutputStream
    - Class ObjectInputStream

    The interface Serializable identifies classes serializable, classes ObjectOutputStream and ObjectInputStream, the mechanisms of serialization and deserialization is to use the abstract. We also have at our disposal the interface Externalize which allows us implement our own serialization mechanism.

    1.1. The interface Serializable
    To serialize an object of a given class, it must implement the interface Serializable or inherit a class itself serializable. The interface Serializable has no attributes and no methods, it is only to identify a class serializable. All object attributes are serialized but under certain conditions.
    To be serialized, an attribute is:

    - itself be serializable or be a primitive type (which are all serializable)
    - not be declared using the static keyword
    - not be declared using the keyword transient
    - not be inherited from a superclass unless it is itself serializable

    1.2. The serialVersionUID
    The serialVersionUID is a "version number" associated with each class implements the interface Serializable which ensures, at the deserialization, the versions of Java classes are consistent. If the test fails, InvalidClassException rose. A serializable class can declare the serialVersionUID explicitly in declaring an attribute named "serialVersionUID" that must be static, Final and type long :
    declaration of serialVersionUID
    Code:
    private static Final long serialVersionUID = 42L;
    If a serializable class does not declare an explicit serialVersionUID, then the Java serialization mechanism computes a default based on various aspects of the class (this process is governed by the Java specification (TM) Object serialization Specification). It is strongly recommended to declare explicit serialVersionUID. Indeed, the calculation of the default based on parameters that can vary depending on the implementation of compiler This can cause InvalidClassException unexpected during deserialization.

  2. #2
    Join Date
    Feb 2010
    Posts
    136

    Re: Binary Serialization in Java

    1.3. The interface ObjectOutput
    The interface ObjectOutput extends the interface DataOutput to add writing objects. Indeed, the interface DataOutput implements methods for writing primitive types, ObjectOutput also implements the opportunity to write tables. This interface is implemented by class ObjectOutputStream.

    1.4. Class ObjectOutputStream
    Class ObjectOutputStream represents "a stream object" which allows serialize an object using the method writeObject(). Here is the same example of this
    Define a class Person serializable
    Code:
    import java.io.Serializable;
    
    Public class Person implements Serializable {
    	static private Final long serialVersionUID = 6L;
    	private String nm;
    	private String frnm; 
    	private Integer a;
    
    	Public Person(String nm, String frnm, Integer a) {
    		this. nm = nm;
    		this. first_name = surname;
    		this. a = a;
    	}
    
    	Public String function toString() {
        [native code]
    }() {
    		return nm + " " + nm + " " + a + " years";
    	} 
    }
    Now proceed to the serialization of an object Person, to create this class SerializationMain following:
    Code:
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    
    Public class SerializationMain {
    
    	static Public void hand(String ... args) {
    		try {
    			// creation a person
    			Person prs = new Person("Dupont", "Jean", 36);
    System.out.System.out.println("creation of : " + prs);
    
    			// opening a flow of Release toward the file "personne.serial"
    			FileOutputStream flotpt = new FileOutputStream("personne.serial");
    
    			// creation a "Flow object " with the flow file
    			ObjectOutputStream objstr= new ObjectOutputStream(flotpt);
    			try {
    				// Serialization : writing of subject in the flow of Release
    				objstr.writeObject(prs); 
    				// we empty the buffer
    				objstr.flush();
    System.out.System.out.println(prs + " has been serialize");
    			} finally {
    				//close of flow
    				try {
    					objstr.close();
    				} finally {
    					flotpt.close();
    				}
    			}
    		} catch(IOException ioe) {
    			ioe.printStackTrace();
    		}
    	}
    }
    1.5. The interface ObjectInput
    The interface ObjectInput extends the interface DataInput to add reading objects. Indeed, the interface DataInput implements methods Reading primitive types, ObjectInput also implements the read objects and pictures.
    This interface is implemented by class ObjectInputStream we will see now.

  3. #3
    Join Date
    Feb 2010
    Posts
    136

    Re: Binary Serialization in Java

    1.6. Class ObjectInputStream
    Now that we've seen how to serialize an object we see how to deserialize. This is obviously the opposite, just as easy to implement. For this we use the method readObject () in class ObjectInputStream.
    deserialize now the person previously serialized.
    Code:
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    
    Public class DeserializationMain {
    
    	static Public void hand(String ... args) {
    		Person p = null;
    		try {
    			// opening a flow Input since the file "personne.serial"
    			FileInputStream flinpstr = new FileInputStream("personne.serial");
    			// creation a "Flow object " with the flow file
    			ObjectInputStream objinstr= new ObjectInputStream(flinpstr);
    			try {	
    				// deserialization : reading of subject since the flow Input
    				p = (Person) objinstr.readObject(); 
    			} finally {
    				// we farm the flow
    				try {
    					objinstr.close();
    				} finally {
    					did.close();
    				}
    			}
    		} catch(IOException ioe) {
    			ioe.printStackTrace();
    		} catch(ClassNotFoundException cnfe) {
    			cnfe.printStackTrace();
    		}
    		if(p != null) {
    			System.out.System.out.println(p + " has been deserialize");
    		}
    	}
    }
    1.7. The transient keyword
    The keyword transient can prevent the serialization of an attribute a class. It is generally used for "sensitive" data such as passwords or simply for attributes that do not need to be serialized. Take the case of our class Person and are adding it password attribute, taking care of the state with the keyword transient :
    Personne.java
    Code:
    import java.io.Serializable;
    
    Public class Person implements Serializable {
    	static private Final long serialVersionUID = 51L
    	private String nm;
    	private String frnm; 
    	private Integer a;
    
    	transient private String pass;
    ...
    }
    You can take the code serialization / deserialization previous to verify that the password attribute is not serialized.

    1.8. Serialization and inheritance
    The opposite serialization inheritance.
    First case, very simple, when a class inherits a class serializable, it behaves as if it had implemented its own interface Serializable. The attributes of the superclass is serialized by implementing thereof.

    Second case, a class implements the interface Serializable and inherits a class not serializable.
    There are two basic points here are:

    - inherited attributes are not serialized.
    - it is necessary that the extended class has a accessible default constructor, otherwise a InvalidClassException adjourned at runtime.

    An illustration of this
    A class has and a non-serializable Class B inheriting has and implementing the interface Serializable.
    A.java
    Code:
    Public class Has {
        protected String str;
        
        // the manufacturer by default is required
        Public Has() {
            this("<default str>");
        }
        Public Has(String str) {
            this. str = str;
        }
    
        Public String function toString() {
        [native code]
    }() {
            return this. str;
        }
    }
    B.java
    Code:
    import java.io.Serializable;
    
    Public class B extends Has implements Serializable {
        static private Final long serialVersionUID = 7L;
        
        private int itg;
        
        Public B(String string, int itg) {
            great(string);
            this. itg = itg;
        }
        Public String function toString() {
        [native code]
    }() {
            return great.function toString() {
        [native code]
    }() + " : " + this. itg;
        }
    }
    Now execute the following code
    Code:
    import java.io.IOException;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    Public class Hand {
    
        static Public void hand(String ... args) {
            try {
                B tst = new B("B1", 1);
    System.out.System.out.println(tst);
    FileOutputStream floutstrm = new FileOutputStream("tst.serial");
    ObjectOutputStream objstrm = new ObjectOutputStream(floutstrm);
                try {
                    objstrm.writeObject(tst);
    objstrm.flush();
                } finally {
                    objstrm.close();
    floutstrm.close();
                }
                tst = new B("B2", 2);
    System.out.System.out.println(tst);
    FileInputStream flinstrm = new FileInputStream("tst.serial");
    ObjectInputStream objstrm = new ObjectInputStream(flinstrm);
                try {
                    tst = (B) objstrm.readObject();
                } finally {
                    try {
                        objstrm.close();
                    } finally {
                        did.close();
                    }
                }
                System.out.System.out.println(tst);
            } catch(ClassNotFoundException cnfe) {
                cnfe.printStackTrace();
            } catch(IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

Similar Threads

  1. binary and text conversion java
    By Ronguor in forum Software Development
    Replies: 1
    Last Post: 14-03-2012, 01:24 PM
  2. Serialization and serialVersionUID in Java
    By pancham in forum Software Development
    Replies: 7
    Last Post: 15-09-2010, 09:38 PM
  3. What does serialization mean in java?
    By Honorata in forum Software Development
    Replies: 3
    Last Post: 24-11-2009, 08:35 AM
  4. JAVA binary tree
    By Daren in forum Software Development
    Replies: 4
    Last Post: 29-09-2009, 12:17 AM
  5. Convert binary to decimal in java
    By Seraphim in forum Software Development
    Replies: 2
    Last Post: 20-05-2009, 09:19 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,714,144,687.65391 seconds with 17 queries