Preparing a Class as a JavaBean

Problem

You have a class that you would like to install as a JavaBean.

Solution

Make sure the class meets the JavaBeans requirements; create a JAR file containing the class, a manifest, and any ancillary entries.

Discussion

There are three kinds of Java components that are called JavaBeans:

  • Visual components for use in GUI builders, as discussed in this chapter.

  • Components that are used in JavaServer Pages (JSP). Examples of these are given in Chapter 18.

  • Enterprise JavaBeans (EJB) has features for building enterprise-scale applications. Creating and using EJB is more involved than regular JavaBeans and would take us very far afield, so EJB is not covered in this book. When you need to learn about EJB functionality, turn to the O’Reilly book Enterprise JavaBeans.

What all three kinds of beans have in common are certain naming paradigms. All public properties should be accessible by get/set accessory methods. For a given property Prop of type Type, the following two methods should exist (note the capitalization):

public Type getProp(  );
public void setProp(Type)

For example, the various AWT and Swing components that have textual labels all have the following pair of methods:

public String getText(  );
public void setText(String newText);

You should use this set/get design pattern (set/get methods) for methods that control a bean. Indeed, this is useful even in non-bean classes for regularity. The “bean containers” -- the Bean Builders, the JSP mechanism, and the ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.