JavaBeans

This is an old revision of this page, as edited by Holly Cheng (talk | contribs) at 23:10, 27 January 2006 (moved Java Beans to JavaBeans: per WP:RM). 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 J2EE.

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

public class PersonBean implements java.io.Serializable {
  private String name;
  private int age;
public PersonBean() { // Our constructor. Note that it takes no arguments. }
public void setName(String n) { this.name = n; }
public void setAge(int a) { this.age = a; }
public String getName() { return (this.name); } public int getAge() { return (this.age); } }
PersonBean person = new PersonBean();
person.setName("Bob");
System.out.println(person.getName());

See also