Java serialization - saving a class definition

I learned a little about serialization in java. My basic understanding is a mechanism for storing the state of an object and writing it to streams, so that we can inflate and use it at any time or in any other "JVM" where the object was not created. Suppose now that if I have a class A and create an instance of class A ie object a, serialize it and save it in the A.ser file. I copy the file to another system and deserialize the "A.ser" file to get the saved state of object a. But in this case, the definition of class A must be present in another system, where I deserialize the object! Is there a way to save even the class definition and transfer it to another system, so that the other JVM has no idea which class A until we deserialize the file, get the class definition and restore the class there?

+4
source share
4 answers

What you are describing is ClassLoader. To be able to load class A in a JVM that does not have A in its classpath, you need to use ClassLoader to load the class (and its dependencies).

Then, ObjectInputSTream must delegate the custom classloader to resolve its classes.

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

+1
source

Let's consider that for de-serialization you do not need classes. But what will you do with this after de-serialization, since you cannot execute an object without defining a class?

This is why de-serialization throws a ClassNotFoundException when it cannot find the class definition. You can spread the definition of your class as a jar.

0
source

Not with serialization, you will have to store class files separately, as well as evaluate dependencies and link them too.

So, you have to serialize the object, find its .class , detect dependent classes, find .class files, and so on, until all dependencies are resolved.

As you could imagine, this is not an easy task, so submit this material with your jar class file and do it.

0
source

One idea is for the host system to load the class definition from the remote registry . You will need to get the name of the class using reflection. Just guess I never tried.

0
source

Source: https://habr.com/ru/post/1392656/


All Articles