Is it safe to use bytecode improvement methods for classes that can be serialized and why?

I haven't tried it yet, but it seems risky. The thing I'm thinking of is tools for simple VO classes with JiBX. These VOs are going to be serialized by AMF and possibly other schemes. Can someone confirm or refute my suspicions that doing things behind my back, such as bytecode amplification, can hurt something in general and provide some background information on why? Also, I'm interested in a specific case of JiBX.

+7
java serialization bytecode-manipulation amf jibx
source share
2 answers

Behind the scenes, serialization uses reflection. Your bytecode manipulation seems to add fields. Thus, if you do not mark these fields as temporary, they will be serialized in the same way as regular fields.

So, if you performed the same bytecode manipulation on both sides, everything will be fine.

If not, you will need to read the serialization documentation to understand how backward compatibility functions work. Essentially, I think you can send fields that are not expected from the recipient, and everything is fine; and you can skip the fields and they will get their default values ​​on the receiving side. But you have to check it in the specification!

If you simply add methods, then they do not affect serialization, unless they are like readResolve() , etc., which are specifically used by the serialization mechanism.

+7
source share

Adding / modifying / deleting public or protected fields or methods for a class will affect its ability to deserialize. Like adding interfaces. They are used, among other things, to generate a serialVersionUID , which is written to the stream as part of the serialization process. If the serialVersionUID class does not match the loaded class during deserialization, it will fail.

If you explicitly set serialVersionUID in your class definition, you can do it. You might want to implement readObject and writeObject .

In extreme cases, you can implement Externalizable and have full control over the entire serialization of the object.

The absolute worst case scenario (albeit incredibly useful in some situations) is to implement writeReplace on a complex object to replace it with a kind of simpler value object in serialization. Then, when deserializing, an object with a simpler value can implement readResolve to either rebuild or find a complex object on the other hand. It's rare when you need to pull it out, but it's terribly fun when you do it.

+2
source share

All Articles