Why is Enum singleton safe for serialization?

Internally, how does serialization / deserialization happen in Enum? How does jvm generate the same hash code before (serialization) and after (deserialization)?

+4
source share
2 answers

Serialization handles enumspecially. Basically, it stores only a link to it classand the name of the constant. During deserialization, this information is used to search for an existing type runtime object enum.

Thus, if you deserialize a constant enumwithin the same runtime, you will get the same runtime instance that you serialized.

JVM - . - . , , , enum, .

+4

, / Enum?

Java. Enum. , enum - , .

jvm - () ()?

, JVM hashCode, JLS , . , JVM 16 Oracle 8 - .

Object[] objs = new Object[5];
for(int i=0;i<objs.length;i++) {
    objs[i] = new Object();
}
RetentionPolicy[] values = RetentionPolicy.values();
System.out.println(objs+": "+objs.hashCode());
for (Object obj : objs) {
    System.out.println(obj+": "+obj.hashCode());
}
for (RetentionPolicy policy : values) {
    System.out.println(policy+": "+policy.hashCode());
}

new Object[5],

[Ljava.lang.Object;@677327b6: 1735600054
java.lang.Object@14ae5a5: 21685669
java.lang.Object@7f31245a: 2133927002
java.lang.Object@6d6f6e28: 1836019240
java.lang.Object@135fbaa4: 325040804
java.lang.Object@45ee12a7: 1173230247
SOURCE: 856419764
CLASS: 621009875
RUNTIME: 1265094477

2, .

[Ljava.lang.Object;@677327b6: 1735600054
java.lang.Object@14ae5a5: 21685669
java.lang.Object@7f31245a: 2133927002
SOURCE: 1836019240
CLASS: 325040804
RUNTIME: 1173230247

, - . Object[].

SOURCE: 1735600054
CLASS: 21685669
RUNTIME: 2133927002

, - , , - - .

. -, .

+2

All Articles