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.
If you are really trying to store the
Classitself: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
Classas parameter for thewriteObjectmethod. Instead of this you should use the instance you have.In the sample, the variable
objectToSerializewill 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.