为什么 Java Bean 必须是可序列化的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3142181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why Java Beans have to be serializable?
提问by Moritz
Is it necessary that a Java Bean implements the Serializableinterface?
Java Bean 是否有必要实现该Serializable接口?
采纳答案by BalusC
It's one of the "typical" features as described in the Javabeans specification.
它是Javabeans 规范中描述的“典型”特性之一。
Here's an extract of chapter 2.1 What is a bean?
这是第2.1章的摘录什么是 bean?
Individual Java Beans will vary in the functionality they support, but the typical unifying features that distinguish a Java Bean are:
- Support for “introspection” so that a builder tool can analyze how a bean works
- Support for “customization” so that when using an application builder a user can customize the appearance and behaviour of a bean.
- Support for “events” as a simple communication metaphor than can be used to connect up beans.
- Support for “properties”, both for customization and for programmatic use.
- Support for persistence, so that a bean can be customized in an application builder and then have its customized state saved away and reloaded later.
各个 Java Bean 支持的功能会有所不同,但区分 Java Bean 的典型统一特性是:
- 支持“内省”,以便构建器工具可以分析 bean 的工作方式
- 支持“自定义”,以便在使用应用程序构建器时,用户可以自定义 bean 的外观和行为。
- 支持“事件”作为一种简单的通信隐喻,可用于连接 bean。
- 支持“属性”,用于定制和编程使用。
- 支持持久性,以便可以在应用程序构建器中自定义 bean,然后保存其自定义状态并稍后重新加载。
And here's an extract of chapter 5.5 Summary of Persistence:
这是第5.5章“持久性摘要”的摘录:
All beans must support either Serialization or Externalization.
所有 bean 必须支持序列化或外部化。
In practice, it's not explicitly necessary for it to function. It will in general also just work fine without implementing Serializable. It's however useful whenever you'd like to store them "plain" on harddisk or send "plain" over network. For example when it's a session scoped bean which is to be stored in the HTTP session and the server is been confugured to persist and revive HTTP sessions during shutdown/restart. At any way, whenever you face a NotSerializableExceptionwith the bean's full qualified classname in the message, then it's enough sign to let it implement Serializable.
在实践中,它没有明确的必要运行。一般来说,它也可以在不实施的情况下正常工作Serializable。无论何时您想将它们“纯”存储在硬盘上或通过网络发送“纯”,它都非常有用。例如,当它是一个会话范围的 bean 时,它将存储在 HTTP 会话中,并且服务器被配置为在关闭/重新启动期间保持和恢复 HTTP 会话。无论如何,每当您NotSerializableException在消息中遇到带有 bean 的完全限定类名的 a 时,就足以让它实现Serializable.
回答by Yuval Adam
Yes.
是的。
By definition - a Java bean is exactly that, a serializablePOJO (plain old Java object), with a no-argument constructor and private fields with getters/setters.
根据定义 - Java bean 就是这样,一个可序列化的POJO(普通的旧 Java 对象),具有无参数构造函数和带有 getter/setter 的私有字段。

