参考链接:
深度分析Java的枚举类型—-枚举的线程安全性及序列化问题
https://www.cnblogs.com/z00377750/p/9177097.html
深入理解Java枚举类型(enum)
https://www.cnblogs.com/alter888/p/9163612.html
枚举使用详解
https://www.jianshu.com/p/174467006572
我们知道,以前的所有的单例模式都有一个比较大的问题,就是一旦实现了Serializable接口之后,就不再是单例得了,因为,每次调用 readObject()方法返回的都是一个新创建出来的对象,有一种解决办法就是使用readResolve()方法来避免此事发生。但是,为了保证枚举类型像Java规范中所说的那样,每一个枚举类型极其定义的枚举变量在JVM中都是唯一的,在枚举类型的序列化和反序列化上,Java做了特殊的规定。原文如下:
Enum constants are serialized differently than ordinary serializable or externalizable objects.
The serialized form of an enum constant consists solely of its name;
field values of the constant are not present in the form.
To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant’s name method.
To deserialize an enum constant, ObjectInputStream reads the constant name from the stream;
the deserialized constant is then obtained by calling the java.lang.Enum.valueOf method,
passing the constant’s enum type along with the received constant name as arguments.
Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.
The process by which enum constants are serialized cannot be customized: any class-specific writeObject, readObject, readObjectNoData, writeReplace,
and readResolve methods defined by enum types are ignored during serialization and deserialization. Similarly, any serialPersistentFields or
serialVersionUID field declarations are also ignored–all enum types have a fixedserialVersionUID of 0L.
Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.
大概意思就是说,在序列化的时候Java仅仅是将枚举对象的name属性输出到结果中,反序列化的时候则是通过java.lang.Enum的valueOf方法来根据名字查找枚举对象。同时,编译器是不允许任何对这种序列化机制的定制的,因此禁用了writeObject、readObject、readObjectNoData、writeReplace和readResolve等方法。
枚举优点
1 增强代码可读性
2 传递参数错误
3 去除equals两者判断 由于常量值地址唯一,使用枚举可以直接通过“==”进行两个值之间的对比,性能会有所提高。
4 编译优势(与常量类相比)
常量类编译时,常量被直接编译进二进制代码中,常量值在升级中变化后,需要重新编译引用常量的类,因为二进制代码中存放的是旧值。枚举类编译时,没有把常量值编译到代码中,即使常量值发生改变,也不会影响引用常量的类。
5 修改优势(与常量类相比)
枚举类编译后默认final class,不允许继承可防止被子类修改。常量类可被继承修改、增加字段等,易导致父类不兼容。
6 枚举型可直接与数据库交互。
7 Switch语句优势
使用int、String类型switch时,当出现参数不确定的情况,偶尔会出现越界的现象,这样我们就需要做容错操作(if条件筛选等),使用枚举,编译期间限定类型,不允许发生越界。
————————————————
版权声明:本文为CSDN博主「1466028300」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_35972907/article/details/97915458