JavaBeans 是 Java 的可重用软件组件。实际上,它们是用符合特定约定的 Java 编程语言编写的类。它们用于将许多对象封装到单个对象(bean)中,以便它们可以作为单个 bean 对象而不是多个单独的对象传递。 JavaBean 是可序列化的 Java 对象,具有 0 参数构造函数,并允许使用 getter 和 setter 方法访问属性。
优势
- Bean 获得了 Java“一次编写,随处运行”范例的所有好处。
- 可以控制暴露给另一个应用程序的 Bean 的属性、事件和方法。
- 可以提供辅助软件来帮助配置 Bean。
- Bean 的配置设置可以保存在持久存储中,并且可以在以后恢复。
- Bean 可以注册以接收来自其他对象的事件,并可以生成发送给它的事件。
缺点
- 具有空构造函数的类可能会在无效状态下被实例化。如果这样的类是由开发人员手动实例化的(而不是由某种框架自动实例化),开发人员可能不会意识到他已将类实例化为无效状态。编译器无法检测到此类问题,即使已记录在案,也不能保证开发人员会看到文档。
- 必须为每个属性创建一个 getter,并为许多、大部分或所有属性创建一个 setter,这会产生大量样板代码。
例子:
package beans;
/**
* Class <code>PersonBean</code>.
*/
public class PersonBean implements java.io.Serializable {
private String name;
private boolean deceased;
static final long serialVersionUID = 1L;
/** No-arg constructor (takes no arguments). */
public PersonBean() {
}
/**
* Property <code>name</code> (note capitalization) readable/writable.
*/
public String getName() {
return this.name;
}
/**
* Setter for property <code>name</code>.
* @param name
*/
public void setName(final String name) {
this.name = name;
}
/**
* Getter for property "deceased"
* Different syntax for a boolean field (is vs. get)
*/
public boolean isDeceased() {
return this.deceased;
}
/**
* Setter for property <code>deceased</code>.
* @param deceased
*/
public void setDeceased(final boolean deceased) {
this.deceased = deceased;
}
}
参考http://en.wikipedia.org/wiki/JavaBeans
根据@Andy 的评论,我接受我们应该声明serialVersionUID。根据Java Docs
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members. Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is waived for array classes.
如果您没有明确指定 serialVersionUID,则会自动生成一个值 - 但这很脆弱,因为它依赖于编译器实现。