维基百科上关于JavaBeans的定义:JavaBeans are reusable software components for Java. Practically, they are classes that encapsulate many objects into a single object (the bean). They are serializable, have a 0-argument constructor, and allow access to properties using getter and setter methods.
可以看出,JavaBeans只是一个标准,遵循这个标准能提高代码的可复用程度,满足以下条件的类就可以说它符合JavaBeans规范:
- 所有的属性都是私有的(private),利用getters/Setters来存取属性
- 有一个公开的且没有参数的构造函数
- 实现Serializable接口,可以保存类的运行状态
JavaBeans 类的一个实例:
package beans;
/**
* Class <code>PersonBean</code>.
*/
public class PersonBean implements java.io.Serializable {
private String name = null;
private boolean deceased = false;
/** No-arg constructor (takes no arguments). */
public PersonBean() {
}
/**
* Property <code>name</code> (note capitalization) readable/writable.
*/
public String getName() {
return name;
}
/**
* Setter for property <code>name</code>.
* @param NAME®
*/
public void setName(final String NAME) {
name = NAME;
}
/**
* Getter for property "deceased"
* Different syntax for a boolean field (is vs. get)
*/
public boolean isDeceased() {
return deceased;
}
/**
* Setter for property <code>deceased</code>.
* @param DECEASED
*/
public void setDeceased(final boolean DECEASED) {
deceased = DECEASED;
}
}