Showing posts with label serialization. Show all posts
Showing posts with label serialization. Show all posts

Serializing and De-serializing a Java object to XML

0

A Java object can be serialized as XML using the XMLEncoder

try { XMLEncoder enc= new XMLEncoder(new BufferedOutputStream( new FileOutputStream("<output xml file>"))); enc.writeObject(instance);//instance is the bean object to be serialized enc.close(); } catch (FileNotFoundException e) { }


De-serializing the XML file can be done as follows using the XMLDecoder


try { XMLDecoder dec= new XMLDecoder(new BufferedInputStream( new FileInputStream("<input xml file>"))); MyClass o = (MyClass)dec.readObject(); dec.close(); } catch (FileNotFoundException e) { }

Read more »
Labels: ,

Using readResolve method to create a Serializable Singleton

0

The readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. The following code demonstrates how to create a serializable singleton , using the method.



public class Singleton implements Serializable {  static Singleton instance= new Singleton (); private Singleton ()  {  } protected Object readResolve()   {   return instance;  } }

Read more »
Labels: ,
© Zone817. Powered by Blogger.