Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java serialization - persist class definition

I have learned a bit on Serialization in java . My basic understanding is it is a mechanism to persist the state of an object and write it to streams so that we can inflate and use it at any latter point in time or in any other "JVM" where the object was not created . Now suppose if I have a class A and create an instance of the class A i.e. object a , serialize it and store it in a file "A.ser" . I copy the file to other system and deserialize the file "A.ser" to obtain the persisted state of the object a . But in that case the class definition of A should be present in the other system where I deserialize the object ! Is there any way we can save even the class definition and transport it to the other system , so that the other JVM does not have any idea of what class A is until we deserialize the file obtain the class definition and reconstruct the class over there ?

like image 672
AllTooSir Avatar asked Nov 14 '22 11:11

AllTooSir


1 Answers

What you describe is a ClassLoader. To be able to load class A in a JVM that doesn't have A in its classpath, you need to use a ClassLoader to load the class (and its dependencies).

The ObjectInputSTream would then have to delegate to the custom class loader to resolve its classes.

See the last post in https://forums.oracle.com/forums/thread.jspa?threadID=1149865 for an example that does that. Spring also has such an ObjectInputStream.

like image 158
JB Nizet Avatar answered Nov 16 '22 03:11

JB Nizet