Java中枚举的反序列化 [英] Deserialization of enum in Java

查看:151
本文介绍了Java中枚举的反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中枚举类型的默认反序列化受到限制,因为 readObject readObjectNoData 抛出 InvalidObjectException .因此,枚举类型非常适合实现单例类而没有任何缺陷(Item 77, Effective Java,第二版,Bloch ).

Default deserialization of of enum types in Java is restricted as the readObject and readObjectNoData throw InvalidObjectException. For this reason enum types are perfect for implementing singleton classes without any flaw (Item 77, Effective Java, 2nd Edition, Bloch).

  • 为什么首先枚举类型完全实现 Serializable ?
  • 在实践中应该如何反序列化枚举引用?

推荐答案

枚举类型实现 Serializable ,因此您可以序列化包含枚举常量的对象.枚举常量的反序列化方式与其他任何objest方法相同:通过使用 ObjectInputStream.readObject().枚举常量的编码方式与普通类的实例不同,因此 ObjectInputStream.readObject()可以反序列化它们而无需调用其 readObject 方法.还有其他使用特殊编码的类,其中包括 String Class .有关更多详细信息,请参见文档.

Enum types implement Serializable so you can serialize objects which contain enum constants. Enum constants are deserialized in the same way as any other objest: by using ObjectInputStream.readObject(). Enum constants are encoded differently than instances of normal classes, so ObjectInputStream.readObject() can deserialize them without calling their readObject method. There are other classes which use special encodings, among them are String and Class. See the documentation for more details.

如果您想自己实现可序列化的单例类,请查看 readResolve 方法.

If you want to implement serializable singleton classes yourself, look at readResolve method.

这篇关于Java中枚举的反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆