Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we don't need to implement Serializable to serialize to xml

By definition, Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized.

But when I used it with XML the object's state was saved into XML without using serializable.

How am I able to do this without Serializable interface?

Below is the attached code :

public class SerializeXml {public static void main(String[] args) {

Student s1=new Student("Sachin",1);
Student s2=new Student("Abhinav",2);


try {
    XMLEncoder x=new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Students.xml")));
    x.writeObject(s1);
    x.writeObject(s2);
    x.close();
    System.out.println("Success");
}


catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();}}}

and here is the Method for storing values

public class Student{ public String name;public int rollno;

   public Student(String Name,int Rollno)
   {
        name=Name;
        rollno=Rollno;

   }

   public Student()
   {
        super();
   }}
like image 224
SK117 Avatar asked Nov 30 '25 06:11

SK117


1 Answers

Java serialization is a specific byte-format for serializing objects, utilizing ObjectOutputStream for serialization and ObjectInputStream for deserialization. Objects are 'enabled' for this type serialization by implementing the marker interface Serializable.

However you are serializing to XML, which has nothing to do with the normal Java serialization mechanism, so you do not need to implement Serializable. Instead you need to follow the 'rules' and expectations of the XML serialization framework you are using.

like image 187
Mark Rotteveel Avatar answered Dec 01 '25 18:12

Mark Rotteveel