javaexceptioninstantiationexceptionxmlencoder

java.lang.Instantiation exception while using XMLEncoder


I am trying to use XMLEncoder in my Java program but i am getting an java.lang.InstantiationException. Follwing is my code that i am using:

   /*
       Method for serialization.
   */
   public void serializeToXml(Object obj) throws FileNotFoundException{

        FileOutputStream fos = new FileOutputStream("/home/neeraj/xmlOP.xml"); 
        XMLEncoder encoder  =  new XMLEncoder(fos);
        encoder.writeObject(obj);
        encoder.close();
    }


   public static void main(String [] args){


        String uuid = UUID.randomUUID().toString();

        SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy");
        Date date = new Date();
        String tDate = format.format(date);

        ClassA a = new  ClassA(uuid,"expense","Pune",tDate,1,200,0,4);
        a.createAssociatedEvents(2);

        serializationExample serializer = new serializationExample();
        try {

            serializer.serializeToXml(a);

        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

}

Apart from this : I have two more classes: classA and the classB. Both the classes implement Serializable. ClassA has an ArrayList of ClassB. All the fields of both the class have getter and setter methods. The exact error (stack-trace) is ;

 java.lang.InstantiationException: classA continuing...

 java.lang.exception :XMLEncoder:discarding statement XMLEncoder.writeObject(classA);
 continuing.

I am not able to figure out what is going wrong or what does these error mean. How should i rectify my code to make things work?

Thanks.


Solution

  • XMLEncoder requires JavaBeans object to serialize it, so you have to define a public default constructor (with no arguments) in ClassA and ClassB.

    JavaBeans convention is here.