Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to deserialize part of an object in Java?

Hypothetical scenario: output stream of objects of type Message that implement Serializable. Message has members Header and Body. Header is small and Body can be large. Say I want to write a filter based on info in the Header: is there a way to do it without having to deserialize Body?

like image 602
user443854 Avatar asked Feb 19 '26 05:02

user443854


2 Answers

You shall NOT serialize Body in the first place by declaring it transient.

But if you already have serialized the Message object, there is no way to selectively deserialize specific members.

like image 107
bragboy Avatar answered Feb 20 '26 17:02

bragboy


You just discovered one of the weaknesses of object-oriented programming compared to databases: "What if I just want half of a Customer object?"

What I would say is that you need to split your Message class into something like MessageHeader, with the header information and no reference to the body, and a MessageBody class that has the body and a key that can be used to look up the header data. Then you need to store and retrieve the serialized MessageHeader and MessageBody objects separately.

like image 29
Luis Casillas Avatar answered Feb 20 '26 19:02

Luis Casillas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!