reflection - Serializing java.lang.class -
i have problem persisting class object in db.
i tried convert object byte array using object objectarrayoutputstream
, bytearrayoutputstream
shown below , persisted byte array:
class klazz = getclassforclassdef(); bytearrayoutputstream baos = new bytearrayoutputstream(); objectoutputstream oos = new objectoutputstream(baos); oos.writeobject(klazz); baos.tobytearray();
but error shown below:
java.lang.classformaterror: incompatible magic value 2901213189 in class file
i think way byte array constructed has problem. don't know how create correct .class
equivalent of class object.
if trying store class
itself:
you can read more here: https://stackoverflow.com/a/2390763/1001027
if trying store object:
you using class
parameter writeobject
method. instead of should use instance have.
// write class bytearrayoutputstream baos = new bytearrayoutputstream(); objectoutputstream oos = new objectoutputstream(baos); oos.writeobject(objecttoserialize); // need store byte[] data = baos.tobytearray(); // read again (just test) bytearrayinputstream bais = new bytearrayinputstream(data); object restored = new objectinputstream(bais).readobject(); // write came deserialization system.out.println(restored);
in sample, variable objecttoserialize
hold object store.
are sure want store java serialized objects database? there few alternatives that. create formal model using orm framework such hibernate.
if think dynamic, use xml serialization such xstream or json serialization, because readable formats, meaning can see stored, avoiding need deserialize java application check state.
Comments
Post a Comment