Donnerstag, 13. Dezember 2012

XML Writable (Serializing) and the InstantiationException

If you want to serialize (encode) non-bean objects in java, you first have to prepare readFields() and writeFields() methods for your it so java has an idea on how the data in the object is meant to be stored and re-created. Shortly, you need to make your object Writable in hadoop terms.

Exception:

java.lang.InstantiationException:
(CLASS NAME YOU ARE TRYING TO SERIALIZE)
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement ArrayList.add(MyObject);
Continuing ...
java.lang.InstantiationException:
(CLASS NAME YOU ARE TRYING TO SERIALIZE)
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement ArrayList.add(MyObject);
Continuing ...

SITUATION BEFORE:

Object class (this is the class of the object you would like to serialize):

public class MyObject {
[VARIABLES]
[CONSTRUCTOR(S)]
[GETTERS&SETTERS]
}

Call from main (encode and print out);

main(String[] args) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
XML encoder = new XMLEncoder(buffer);
encoder.writeObject(javaBean);
encoder.close();
System.out.println(buffer.toString());
}


AFTER:

public class MyObject implements Writable {
[VARIABLES]
[CONSTRUCTORS]
[GETTERS&SETTERS]

@Override
writefields() throws IOException {
WritableUtils.writeString(out, variable1);
WritableUtils.writeString(out, variable2);
WritableUtils.writeString(out, variable3);
}

@Override
readFields() throws IOException {
variable1 = WritableUtils.readString(in);
variable2 = WritableUtils.readString(in);
variable3 = WritableUtils.readString(in);
}

}

The call in main is the same..

It is very important that the order of variables in read and write are the same. If you put variable1 in the first place of writeFields(), it needs to be on the first place on readFields() too so it can be put back correctly. Also your class MUST have a no-args constructor.

Keine Kommentare:

Kommentar veröffentlichen