Dude Dawg
Dude Dawg

Reputation: 1505

Why can't Constructors objects be serialized in Java?

I have a class that implements Serializable, it's part of a bigger mesh of objects, it contains a Constructor field, but when it's the Constructors turn to be serialized it throws the NotSerializableException.

I guess I'll have to write the logic myself and recreate the constructor myself every time I deserialize the containing object, but why the heck on earth would the designers of Java wanna create such hassle in the first place? I realize that the ClassLoader is needed to figure out the identity of a class, and that the ClassLoader itself will not be serialized and deserialized, but shouldn't the constructor remember the string arguments used to create it?

Upvotes: 0

Views: 524

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308149

Yes, as you realized Constructor is not serializable.

You need to make the Constructor field transient and restore it manually, when needed.

Yes, the Java designers could have made the Constructor class serialized down to the class name and argument list, but that would open a huge can of worms, basically boiling down to the fact that in any given JVM there can be an arbitrary number of classes with that name and there's no sane way to know which one to use when deserializing such an object.

Upvotes: 3

Related Questions