Kalpana Kalpana (Editor)

JavaBeans

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit

In computing based on the Java Platform, JavaBeans are classes that encapsulate many objects into a single object (the bean). They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name "Bean" was given to encompass this standard, which aims to create reusable software components for Java.

Contents

Advantages

  • The properties, events, and methods of a bean that are exposed to another application can be controlled.
  • A bean may register to receive events from other objects and can generate events that are sent to those other objects.
  • Auxiliary software can be provided to help configure a java bean.
  • The configuration settings of a bean can be saved to persistent storage and restored.
  • Disadvantages

  • A class with a nullary constructor is subject to being instantiated in an invalid state. If such a class is instantiated manually by a developer (rather than automatically by some kind of framework), the developer might not realize that the class has been improperly instantiated. The compiler cannot detect such a problem, and even if it is documented, there is no guarantee that the developer will see the documentation.
  • JavaBeans are inherently mutable and so lack the advantages offered by immutable objects.
  • Having to create getters for every property and setters for many, most, or all of them can lead to an immense quantity of boilerplate code.
  • JavaBeans API

    The JavaBeans functionality is provided by a set of classes and interfaces in the java.beans package.

    JavaBean conventions

    In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behaviour. These conventions make it possible to have tools that can use, reuse, replace, and connect Java Beans.

    The required conventions are as follows:

  • The class must have a public default constructor (with no arguments). This allows easy instantiation within editing and activation frameworks.
  • The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.
  • The class should be serializable. [This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the VM and of the platform.]
  • Code Example

    TestPersonBean.java:

    Use in a JavaServer Page

    testPersonBean.jsp;

    References

    JavaBeans Wikipedia