JavaBeans

This is an old revision of this page, as edited by 200.199.82.174 (talk) at 12:13, 30 March 2006 (JavaBean conventions). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

JavaBeans are software components written in the Java programming language.

The JavaBeans specification by Sun Microsystems defines them as "reusable software components that can be manipulated visually in a builder tool".

In spite of many similarities, JavaBeans should not be confused with Enterprise JavaBeans (EJB), a server-side component technology that is part of Java EE.

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 should be serializable (able to persistently save and restore its state)
  • It should have a no-argument constructor
  • Its properties should be accessed using get and set methods that follow a standard naming convention
  • It should 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. However, this view is misleading for Java Beans that support event handling, because the method conventions and associated support classes for event handling are fairly intricate, and require the use of specific base classes and interfaces.

JavaBean Example

// PersonBean.java

public class PersonBean implements java.io.Serializable {
    private String name;
    private boolean deceased;

    // Default constructor (takes no arguments).
    public PersonBean() {
    }

    public String getName() {
        return (this.name);
    }
    public void setName(String n) {
        this.name = n;
    }
    // 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(true);

        // Output: "Bob [deceased]"
        System.out.print(person.getName());
        System.out.println(person.isDeceased() ? " [deceased]" : "");
    }
}

See also