Search code examples
javareflectionclassloaderbinary-serialization

Serializing java.lang.class


I have a problem persisting the Class object in the DB.

I tried to convert the object into a byte array using object ObjectArrayOutputStream and ByteArrayOutputStream as shown below and persisted it the byte array:

Class klazz = getClassForClassDef();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(klazz);
baos.toByteArray();

But I get an error shown below:

java.lang.ClassFormatError: Incompatible magic value 2901213189 in class file

I think that the way byte array was constructed has the problem. But I don't know how to create a correct .class equivalent of the class object.


Solution

  • If you are really trying to store the Class itself:

    You can read more about it here: https://stackoverflow.com/a/2390763/1001027

    If you are trying to store an Object:

    You are using the Class as parameter for the writeObject method. Instead of this you should use the instance you have.


    // write the class
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(objectToSerialize);
    
    // this you need to store
    byte[] data = baos.toByteArray();
    
    // read it again (just a test)
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    Object restored = new ObjectInputStream(bais).readObject();
    
    // write what came from the deserialization
    System.out.println(restored);
    

    In the sample, the variable objectToSerialize will hold the object to store.


    Are you sure you want really store java serialized objects into your database? There are a few alternatives to that. You could create a formal model using an ORM framework such as Hibernate.

    If you think this would be too dynamic, you could use XML serialization such as XStream or even JSON serialization, this would be good because they are readable formats, meaning you can see what is really stored, avoiding the need to deserialize it with a Java application just to check the state.