JavaBean

From Wikipedia, the free encyclopedia

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".

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.

Contents

[edit] 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:

  • It has to have a no-argument constructor
  • Its properties must be accessible using get, set and other 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.

[edit] 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]");
    }
}

[edit] 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.

[edit] See also

[edit] External links