Why is there a serialVersionUID field?

This confused me from starting the interface Serializable, why should I include this field in all my classes. I understand that this interface needs a unique identifier to label the class, but why they cannot generate this at runtime. For example, they could generate it using an MD5 hash of a fully qualified class name or a similar methodology used to handle duplicates in their rare occurrence (which, I am sure, is what eclipse does when asked to generate an identifier).

So what I ask (no, this message is not just a rant against the standard library), then how exactly does the serialization field use the framework?

The reason I would like to know is because I will try to create an Aspect (in AspectJ or another language) that will add a serialVersionUID field using an MD5 hash and be able to handle conflicts in a way that is acceptable to the API.

I will post the results if I can get it to work.

+3
source share
4 answers

No need to have a box serialVersionUID. If you do not provide one, Java will generate one based on the fields and methods of your class.

, serialVersionUID, , , . :

public class Person implements Serializable {
    private String name;
    public String getName() {
        return name;
    }
}

serialVersionUID. serialver Person, :

Person:    static final long serialVersionUID = 3793453319058452486L;

, .

public class Person implements Serializable {
    private String name;
    public String getName() {
        return name;
    }
    public Object foo() {
        return "bar";
    }
}

- , serialVersionUID :

Person:    static final long serialVersionUID = -6188734029437600310L;

serialVersionUID serialVersionUID. serialVersionUID, ( 1L) , .

. " serialVersionUID ?" .

+9

.

, .

Aspect ( AspectJ ), serialVersionUID, MD5

. , . - , , . , , , . . .

+4

Serializable

java.io. , write save . swing, , JVM , .. Your class.

SerialVersionUID

serialVersionUID Serializable. serialVersionUID, JVM will did it for you automatically, Serializable, Java(TM) Object Serialization Specification

0

@Steve Kuo, serialVersionUID.

, , , , . , private static final long serialVersionUID = 1L; ( Longs...)

, , , Serializable.

, :

public class PersonDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    private String firstName;
    private String lastName;

    // Appropriate getters/setters of course
}

, private String middleInitial.

If we were to load serialVersionUID by 2, we could use this to indicate that the class has changed, and older already serialized instances of PersonDTO with serialVersionUID cannot be deserialized with this changed class definition.

0
source

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


All Articles