Search code examples
javahibernateserializationpojo

Java: does Serialization also write method code to stream for Hibernate entities?


As an experiment, I fetched a Hibernate entity pojo through 'load' and wrote it to a file through normal serialization. I read that file through a separate program again through normal deserialization, and then used reflection to find the fields and the methods that the entity object's proxy class contained.

What surprised me was that it showed me all the methods that the proxy class had in it (e.g. 'getHibernateLazyInitializer()' or 'CGLIB$SET_THREAD_CALLBACKS(net.sf.cglib.proxy.Callback[])' etc.)

What's more, I was able to call 'getHibernateLazyInitializer()' method on the deserializaed instance! Now, if the proxy code is generated dynamically, and if that class does not exist after the JVM in which it was created shuts down, how was I able to call that method? Does the method byte code too get serialized/deserialized for Hibernate pojo's through their proxies?


Solution

  • Ok, I debugged some more and found out that while serializing a proxied instance, Hibernate actually writes an instance of SerializableProxy. This happens because the proxy class implements an interface 'HibernateProxy' which has a 'writeReplace()' method in it which returns the said SerializableProxy instance.

    When this instance is deserialized, SerializableProxy's readResolve() kicks in and returns a HibernateProxy object which is created based on the info mentioned in the SerializableProxy instance, and which uses CGLib Enhancer in turn. That's why I was able to see all those methods and call them too.

    Bottom line: no method code is being written in the stream. Hibernate changes the object itself through writeReplace, and then uses readResolve and CGLIb to recreate the proxy when that object is read back.