JavaBeans are classes written in the Java programming language. They are used to encapsulate many objects into a single object (the bean), so that the bean can be passed around rather than the individual objects.
The specification by Sun Microsystems defines them as "reusable software components that can be manipulated visually in a builder tool".
JavaBean conventions
In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.
The required conventions are:
- The class must have a no-argument constructor
- Its properties must be accessible using get, set and other methods (so called accessor methods) following a standard naming convention
- The class should be serializable (able to persistently save and restore its state)
- It should not contain any required event-handling methods
Because these requirements are largely expressed as conventions rather than by implementing interfaces, some developers view Java Beans as Plain Old Java Objects that follow certain naming conventions..
JavaBean Example
// PersonBean.java
public class PersonBean implements java.io.Serializable {
private String name;
private boolean deceased;
// No-arg constructor (takes no arguments).
public PersonBean() {
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// Different semantics for a boolean field (is vs. get)
public boolean isDeceased() {
return this.deceased;
}
public void setDeceased(boolean deceased) {
this.deceased = deceased;
}
}
// TestPersonBean.java
public class TestPersonBean {
public static void main(String[] args) {
PersonBean person = new PersonBean();
person.setName("Bob");
person.setDeceased(false);
// Output: "Bob [alive]"
System.out.print(person.getName());
System.out.println(person.isDeceased() ? " [deceased]" : " [alive]");
}
}
Adoption
AWT, Swing, and SWT, the major Java GUI toolkits, use JavaBeans conventions for its components, which allows GUI editors like the Eclipse Visual Editor to maintain a hierarchy of components and to provide access to their properties via getters and setters.
See also
- Widgets
- For a server side discussion of Java Beans see Enterprise JavaBeans.