Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

java - Why isn't the serialVersionUID automatically generated?

Why isn't the serialVersionUID automatically generated? I was running into an issue on an application server where apparently an old class was being cached.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

serialversionuid is not automatically generated because it is dangerous. When serialversionuid is set, it implies that two versions of a class are compatible with respect to serialization.

Imagine you have a class called Foo, and it has no serialversionuid (the default), and you serialize an instance of Foo to a file. Later, you add some new members to the Foo class. If you try to deserialize the Foo object from the file, you will get a serialization failure stating that the objects are incompatible. They are incompatible, this is what you want and is the default. They are incompatible because new members in the Foo class cannot be initialized from the old serialized instance of Foo.

Now, you might say, "I don't care, in my application it is acceptable for those fields to be uninitialized". If that really is the case, you can set the serialversionuid of the new Foo class to be the same as the old Foo class. This will tell Java that the objects are compatible with respect to serializablity, and Java will not complain when you deserialize the old Foo instance into the new Foo class (but the new fields will still be uninitialized).

If you are creating a new class for the first time, and you set the serialversionuid, you are entering a contract. That contract is, "For all future versions of this class with the same serialversionuid, I will guarantee they are compatible with respect to state and serialization".

If you change a class, and you explicitly want to disallow deserialization of old versions, you can change the serialversionuid to a new value. This will cause an exception to be thrown if an old object is attempted to be deserialized into a new class instance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...