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();
}}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With