3

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.

user3686864
  • 337
  • 2
  • 5
  • 13

1 Answers1

6

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.

Teletha
  • 419
  • 1
  • 3
  • 7
  • well your answer worked fine, thanks for that, but now i still have one more question, How can I give specific names to the elements in xml, now what i have in the xml is a very long format . it want the elements as value – user3686864 Jul 13 '14 at 18:12
  • what i have now is : 4 which is vey long and confusing to read – user3686864 Jul 13 '14 at 18:14
  • 2
    @user3686864 it sounds like you need to look at a library like [XStream](http://xstream.codehaus.org) instead of using XMLEncoder. – Ian Roberts Jul 13 '14 at 18:15
  • Unfortunately, XMLEncoder doesn't provide such a fucntionality you want. – Teletha Jul 13 '14 at 18:23