Reputation: 27455
I have the following declaration of the static type Object
:
Integer typeId;
//Obtaining typeId
Object containerObject = ContainerObjectFactory.create(typeId);
The factory can produce different types of container objects
, e.g. Date
, Integer
, BigDecimal
and so forth.
Now, after creating the containerObejct
I need to serialize it to an object of type String
and store it into a database with hibernate. I'm not going to provide Object-relational mapping because it doesn't relate to the question directly.
Well, what I want to do is to serialize the containerObject
depending on it runtime-type and desirialize it later with the type it was serialized. Is it ever possible? Could I use xml
-serialization for those sakes?
Upvotes: 0
Views: 4657
Reputation: 16625
There are numerous alternatives, and your question is quite broad. You could:
One key feature you mention is that the object type needs to be embedded in the serialised data. Native Java serialisation embeds the type in the data so this is a good candidate. This is a double-edged sword however, as this makes the data brittle - if at some time in the future you changed the fully qualified class name then you'd no longer be able to deserialise the object.
Gson, on the other hand, doesn't embed the type information, and so you'd have to store both the JSON and the object type in order to deserialise the object.
XML and JSON have advantages that they're a textual format, so even without deserialising it, you can use your human eyes to see what it is. Base64 encoded Java serialisation however, is an unintelligible blob of characters.
Upvotes: 3
Reputation: 9717
There are multiple ways, but you need custom serialization scheme, e.g.:
D|25.01.2015
I|12345
BD|123456.123452436
where the first part of the String represents the type and the second part represents the data. You can even use some binary serialization scheme for this.
Upvotes: 0