AllTooSir
AllTooSir

Reputation: 49372

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 ?

Upvotes: 5

Views: 1404

Answers (4)

JB Nizet
JB Nizet

Reputation: 691755

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.

Upvotes: 1

blackcompe
blackcompe

Reputation: 3190

One idea is to have the receiving system download the class definition from a remote registry. You'll have to get the name of the class using reflection. Just a guess, I've never tried it.

Upvotes: 0

Maurício Linhares
Maurício Linhares

Reputation: 40333

Not with serialization, you would have to store the class files in separate and also evaluate dependencies and bundle them too.

So, you would have to serialize the object, find it's .class file, detect dependent classes, find their .class files too and on and on until you have resolved all dependencies are resolved.

As you might imagine, this is not a simple task, so send this stuff with your classes jar file and be done with it.

Upvotes: 0

Pragalathan  M
Pragalathan M

Reputation: 1781

Lets consider that for de-serialization you dont need the classes. But what will you do with that after de-serialization as you can't execute the object with out class definition?

Thats the reason why de-serialization throws ClassNotFoundException when it can't find the class definition. You can distribute your class definition as a jar.

Upvotes: 0

Related Questions