JavaBeans Conventions - notesvillage

rangesatanskingdomSoftware and s/w Development

Dec 2, 2013 (4 years and 29 days ago)

122 views

JAVABEANS

1

What is a JavaBean?

1

Advantages of JavaBeans

1

Basic Bean Concepts

1

JavaBeans Conventions

2

Class name

3

Superclass

3

Instantiation

3

Bean name

3

Bean Implementation

4

Events

6

Event class

6

Listener interface

7

Listener methods

7

Listener registration

7

Unicast events

7

Special Events

8

Bound Properties

9

C
onstrained Properties

11

Methods

13

Auxiliary Classes

13

Introsp
ection and Bean Info class

14

Locating BeanInfo Classes

19

Customization

20

Persistence

24

Serialization

25


1

JavaBeans

What is a JavaBean?

A JavaBean is a software component that has been designed to be reusable in a
variety

of different environments.

A
Bean
is an instance of a Java class, although in
common terminology, the class itself may also refer to as a Bean.

Beans are important
because they allow you to build
complex systems from simple software components.
JavaBeans
defines an architecture that specifies how these software components (building
blocks) can operate together.

Advantages of JavaBeans

Software component architecture provides standard mechanism to deal with
software building blocks. The following list enum
erates some of the specific benefits that
Java technology provides for a component developer:



A
Bean obtains all the benefits of Java’s “write
-
once, run
-
anywhere” paradigm.



The properties, events and methods of a Bean that are exposed to an application
bui
lder tool can be controlled.



A Bean can be designed to operate correctly in different locales, which makes it
useful in the global markets



Auxiliary components can be provided to help a person configure a Bean. This
software is only needed when the design
-
time parameters for that component
are being set. It does not need to be included in the
run
-
time environment.



The configuration setting of a Bean can be saved in a persistent storage and
restored at a later time.



A Bean may register to receive events fro
m other objects and can generate
events that are send to other objects.

Basic Bean Concepts

Individual Java Beans will vary in functionality, but most shares certain common
defining features.


2



Support for
introspection

allowing a builder tool to analyze h
ow a bean
works.



Support for
customization

allowing a user to alter the appearance and
behavior of a bean.



Support for
events

allowing beans to fire events, and informing builder tools
about both the events they can fire and the events they can handle.



Support for
properties

allowing beans to be manipulated programmatically,
as well as to support the customization mentioned above.



Support for
persistence

allowing beans that have been customized in an
application builder to have their state saved and res
tored. Typically
persistence is used with an application builder’s save and load menu
commands to restore any work that has gone into constructing an application.

Any object that conforms to certain basic rules can be a bean; there is no
Bean

class all be
ans is required to subclass. Many beans are AWT components, but it is also
quite possible, and often useful, to write “invisible” beans that do not have an onscreen
appearance.

JavaBeans Conventions

The JavaBeans component model relies on a number of rule
s and conventions
bean developers must follow. These conventions are not part of the JavaBeans API itself,
but in many ways, they are more important to bean developers than the API itself. The
conventions are sometimes referred to as
designpatterns
; they s
pecify such things as
method names and signatures for property accessor methods defined by a bean.

The reason for these design patterns is interoperability between beans and the
beanbox programs that manipulate them. As we

ve seen, beanbox programs may re
ly on
introspection to determine the list of properties, events, and methods a bean supports. In
order for this to work, bean developers must use method names the beanbox can
recognize. The JavaBeans framework facilitates this process by establishing namin
g

3

conventions. One such convention, for example, is that the getter and setter accessor
methods for a property should begin with
get

and
set
.

Not all the patterns are absolute requirements. If a bean has property accessor
methods that do not follow the na
ming conventions, it is possible to use a
PropertyDescriptor

object (specified in a
BeanInfo

class) to indicate the accessor
methods for the property. Although the
BeanInfo

class provides an alternative to the
property
-
accessor
-
method naming convention, th
e property accessor method must still
follow the conventions that specify the number and type of its parameters and its return
value.

Beans

A bean itself must adhere to the following conventions:

Class name

There are no restrictions on the class name of

a bean.

Superclass

A bean can extend any other class. Beans are often AWT or Swing components,
but there are no restrictions.

Instantiation

A bean must provide a no
-
parameter constructor or a file that contains a serialized
instance the beanbox can de
serialize for use as a prototype bean, so a beanbox can
instantiate the bean. The file that contains the bean should have the same name as the
bean, with an extension of
.ser
.

Bean name

The name of a bean is the name of the class that implements it or th
e name of the
file that holds the serialized instance of the bean (with the
.ser

extension removed and
directory separator (
/
) characters converted to dot (
.
) characters).


4

Bean Implementation

There is no restriction on the capability of a Bean. It may be
as simple as a button,
or a complex function, such as forecasting the performance of a stock portfolio.
The most
basic kind of Bean exposes a number of properties by following a few simple rules
regarding method names.


A bean is characterized by the prope
rties, events, and methods it exports. A
property

is a piece of the bean’s internal state that can be programmatically set and/or
queried, usually through a standard pair of
get

and
set

accessor methods.

A property is a subset of a Bean’s state. The value
s assigned to the property
determine the behavior and appearance of that component.

In general, a Bean provides
two methods for each property: a method to get the property and one to set the property.

A simple property has a single value.

Together these me
thods are known as accessors.
Figure 1 shows a simple Bean with two properties.

package simpleBean.example;

public class SimpleBean{

private String name;

private String password;

public Sring getName(){return name;}

public void setName(String name){ this.n
ame = name;}

public Sring getPassword(){return password;}

public void setPassword (String name){ this.password = password;}

}


Figure 1: A Simple Bean

This Bean could be used to authenticate a user using the name and password. In
general, for any property
named

P

of type
T
, the get method will return an element of the
type
T

and has the following syntax:

public T getP();


5

The one exception is that if the type is Boolean, the get methods may be called using
the syntax:

public boolean isP();

Similarly, the set

method will accept an argument of type
T
, and will use the syntax:

Public void setP(T);

There is no restriction on the type; it may be something simpl
e, such as an integer
or string, or it may be a class or an interface type. The type can also be an array

of
another type, in which case the property is called an
indexed property
. An indexed
property consists of multiple values.
The accessor methods operate on the whole array
and the Bean may wish to provide methods to operate on the individual elements.
Ind
exed property can be identified by the following design patterns:

public T getP(
int
);

Public void setP(
int,
T);

public T
[]

getP();

Public void setP(T
[]
);

Figure 2 shows an example of using an indexed property

package simpleBean.example;

public class
Array
Bean{

private String
things[]
;

public Sring
[]

get
Things
(){return
things
;}

public void set
Things

(String
things
){ this.
things

=
things
;}

public Sring get
Things

(
int i
){return
things[i]
;}

public void set
Things

(
int i,
String
things){ things[i]

=
things
;}

}

F
igure 2
: A
Bean with an array property.

A read/write property has both of these methods to access its values. A read


only property has only get method. A write


only property has only a set method.
Although it is customary to provide both acc
essor metho
ds, doing so is not necessary. We
can read


only properties and/or write


only properties.


6

Indexed property accessor methods can throw any type of checked or unchecked
exceptions. In particular, they should throw an
ArrayIndexOutOfBoundsException

if
the
supplied index is out of bounds.

Events

A bean communicates with the application in which it is embedded and with other
beans by generating
events
. The JavaBeans API uses the same event model AWT and
Swing components use. This model is based on the
java.u
til.EventObject

class and
the
java.util.EventListener

interface. In brief, the event model works like this:



A bean defines an event if it provides
add

and
remove

methods for registering and
deregistering listener objects for that event.



An application th
at wants to be notified when an event of that type occurs uses
these methods to register an event listener object of the appropriate type.



When the event occurs, the bean notifies all registered listeners by passing an
event object that describes the even
t to a method defined by the event listener
interface.

A
unicast event

is a rare kind of event for which there can be only a single registered
listener object. The
add

registration method for a unicast event throws a
TooManyListenersException

if an attemp
t is made to register more than a single
listener.

Beans were originally designed as graphics components, such as buttons or
menus. In this role, a Bean would be driven by events
, such as a user clicking a button.
Other Beans would need to listen for a se
t of events and react appropriately. This leads to
an event


based communication mechanism being incorporated into the Bean
specification, and this mechanism turns out to be useful for server


side program as well.

Event programming is almost easy as pro
perty programming and once again expressed
mostly as a set of naming conventions. An event named
E

should follow these
conventions:

Event class

The event class should directly or indirectly extend
java.util.EventObject

and
should be named
E
Event
.


7

Listen
er interface

The event must be associated with an event listener interface that extends
java.util.EventListener

and is named
E
Listener
.

Listener methods

The event listener interface can define any number of methods that take a single
argument of type
E
E
vent

and return
void
.

Listener registration

The bean must define a pair of methods for registering event listeners that want to
be notified when an
E

event occurs. The methods should have the following signatures:

public void add
E
Listener(
E
Listener)

pub
lic void remove
E
Listener(
E
Listener)

Unicast events

A unicast event allows only one listener object to be registered at a single time. If
E

is a unicast event, the listener registration method should have this signature:

public void

add
E
Listener(
E
Listener
) throws TooManyListenersException

Figure 3 shows an example of an event.

p
ackage eventBean.example;

p
ublic class PurchaseEvent extends Java.util.EventObject{

p
rivate String itemName;

p
ublic PurchaseEvent(Object source, String itemName){

s
uper(source);

t
hi
s.itemName=itemName;


}

p
ublic String getItemName(){return itemName;}

}


Figure 3: An Event class


8

Once the event has been defined, it is necessary to define an interface that will listen
for the event of that type such as the one in figure 4. liste
ners are defined as interfaces
which allows any class to declare that it will listen for any set of events.



p
ackage eventBean.example;

p
ublic
interface

Purchase
Listener

extends Java.util.Event
Listener
{

p
ublic
void
Purchase
Made
(
PurchaseEvent e)
{
}

}


Figur
e 4: An Event
listener

interface


Special Events

In the Bean sense, special events refer to a couple of event type that is of
particular interest to Bean authors working with JSPs. The first is called
PropertyChange
Event
. A Bean fire a
PropertyChange
Event

when

one of its
properties changes, in order to alert other Beans to the change.
A property that generates

a
PropertyChange
Event
,
when the property is modified, is called a
bounded property
.

A Bean can also refuse to set a property to a new value, by gener
ating a
VetoEvent
. This is typically thrown when another object tries to set a property to an
unacceptable value. The inventory Bean might throw this exception if some one tries to
change the number of items it is holding to
-
1. a property that can generat
e a
VetoEvent

is known as a
constrained property.

The JavaBeans API supports two mechanisms for working with properties at a
more advanced level: bound and constrained properties. Bound properties are properties
that provide notifications to an interested
party based on changes in the property value.
An interested party is an applet, application, or bean that needs to know about changes in
the property. These properties are called bound properties because they are bound to
some type of external behavior bas
ed on their own changes. Bound properties are defined

9

at the component level, which means that a bean is responsible for specifying which
components are bound. An example of a bound property is a visibility property, which a
bean's container might be inter
ested in knowing the status of because it would need to
graphic
ally reorganize other beans based on a bean's visibility.

A
bound property

is one that sends a
PropertyChangeEvent

to any interested
PropertyChangeListener

objects whenever the value of the p
roperty changes. A
constrained property

is one that can have any changes vetoed by any interested listener.
When the value of a constrained property of a bean changes, the bean must send out a
PropertyChangeEvent

to the list of interested
VetoableChangeLis
tener

objects. If any
of these objects throws a
PropertyVetoException
, the property value is not changed,
and the
PropertyVetoException

is propagated back to the property setter method.

Bound Properties

A bound property is one that generates a
PropertyCha
ngeEvent

when its value
changes. Here are the conventions for a bound property:

Accessor methods


The getter and setter methods for a bound property follow the same conventions
as a regular property.

Introspection


A beanbox cannot distinguish a bound pr
operty from a nonbound property
through introspection alone. Therefore, you may want to implement a
BeanInfo

class
that returns a
PropertyDescriptor

object for the property. The
isBound()

method of
this
PropertyDescriptor

should return
true
.


10

Listener regi
stration


A bean that defines one or more bound properties must define a pair of methods
for the registration of listeners that are notified when any bound property value change.
The methods must have these signatures:

public void addPropertyChangeListene
r(PropertyChangeListener)

public void removePropertyChangeListener(PropertyChangeListener)


Named property listener registration


A bean can optionally provide additional methods that allow event listeners to be
registered for changes to a single bound pro
perty value. These methods are passed the
name of a property and have the following signatures:

public void addPropertyChangeListener(String,






PropertyChangeListener)

public void removePropertyChangeListener(String,






PropertyChangeListener)

Per
-
property listener registration


A bean can optionally provide additional event listener registration methods that
are specific to a single property. For a property
p
, these methods have the following
signatures:

public void add
P
Listener(PropertyChangeList
ener)

public void remove
P
Listener(PropertyChangeListener)

Methods of this type allow a beanbox to distinguish a bound property from a
nonbound property.

Notification


When the value of a bound property changes, the bean should update its internal
state to

reflect the change and then pass a
PropertyChangeEvent

to the

11

propertyChange()

method of every
PropertyChangeListener

object
registered for the bean or the specific bound property.

Support


java.beans.PropertyChangeSupport

is a helpful class for
implemen
ting bound properties.

Constrained Properties

A constrained property is one for which any changes can be vetoed by registered
listeners. Most constrained properties are also bound properties. Here are the conventions
for a constrained property:

Getter


T
he getter method for a constrained property is the same as the getter method for
a regular property.

Setter


The setter method of a constrained property throws a
PropertyVetoException

if the property change is vetoed. For a property
p

of type
T
, the signa
ture looks like this:


public void set
P
(
T
) throws PropertyVetoException

Listener registration


A bean that defines one or more constrained properties must define a pair of
methods for the registration of listeners that are notified when any constrained pr
operty
value changes. The methods must have these signatures:

public void


addVetoableChangeListener(VetoableChangeListener)

public void


removeVetoableChangeListener(VetoableChangeListener)


12

Named property listener registration


A bean can optionally pro
vide additional methods that allow event listeners to be
registered for changes to a single constrained property value. These methods are passed
the name of a property and have the following signatures:

public void addVetoableChangeListener(String,






VetoableChangeListener)

public void removeVetoableChangeListener(String,






VetoableChangeListener)


Per
-
property listener registration


A bean can optionally provide additional listener registration methods that are
specific to a single constrained pro
perty. For a property
p
, these methods have the
following signatures:

public void add
P
Listener(VetoableChangeListener)

public void remove
P
Listener(VetoableChangeListener)


Notification


When the setter method of a constrained property is invoked, the bean

must
generate a
PropertyChangeEvent

that describes the requested change and pass that
event to the
vetoableChange()

method of every
VetoableChangeListener

object registered for the bean or the specific constrained property. If any listener vetos the
chang
e by throwing a
PropertyVetoException
, the bean must send out another
PropertyChangeEvent

to revert the property to its original value, and then it should
throw a
PropertyVetoException

itself. If, on the other hand, the property change
is not vetoed, the b
ean should update its internal state to reflect the change. If the
constrained property is also a bound property, the bean should notify
PropertyChangeListener

objects at this point.


13

Support


java.beans.VetoableChangeSupport

is a helpful class for
impleme
nting constrained properties.

Methods

A beanbox can expose the methods of a bean to application designers. The only
formal convention is that these methods must be declared
public
. The following
guidelines are also useful, however:

Method name


A method
can have any name that does not conflict with the property
-

and event
-
naming conventions. The name should be as descriptive as possible.

Parameters


A method can have any number and type of parameters. However, beanbox
programs may work best with no
-
param
eter methods or methods that have simple
primitive parameters.

Excluding methods


A bean can explicitly specify the list of methods it exports by providing a
BeanInfo

implementation.

Documentation


A bean can provide user
-
friendly, human
-
readable localiz
ed names and
descriptions for methods through
MethodDescriptor

objects returned by a
BeanInfo

implementation.

Auxiliary Classes

A bean can provide the following auxiliary classes:

BeanInfo



14

To provide additional information about a bean
B
, implement the
BeanInfo

interface in a class named
B
BeanInfo
.

Property editor for a specific type


To enable a beanbox to work with properties of type
T
, implement the
PropertyEditor

interface in a class named
T
Editor
. The class must have a no
-
parameter constructor.

Pr
operty editor for a specific property


To customize the way a beanbox allows the user to enter values for a single
property, define a class that implements the
PropertyEditor

interface and has a no
-
parameter constructor, and register that class with a
Prop
ertyDescriptor

object
returned by the
BeanInfo

class for the bean.

Customizers


To define a customizer, or wizard, for configuring a bean
B
, define an AWT or
Swing component with a no
-
parameter constructor that does the customization. The class
is commonl
y called
B
Customizer
, but this is not required. Register the class with the
BeanDescriptor

object returned by the
BeanInfo

class for the bean.

Documentation


Define default documentation for a bean
B

in HTML 2.0 format and store that
documentation in a fi
le named
B
.html
. Define localized translations of the
documentation in files by the same name in locale
-
specific directories.


Introspection

and Bean Info class

Because Java allows dynamic loading of classes, beanbox programs can load
arbitrary beans. The

beanbox tool uses a process called
introspection

to determine the
properties, events, and methods exported by a bean. The introspection mechanism is

15

implemented by the
java.beans.Introspector

class; it relies on both the
java.lang.reflect

reflection mecha
nism and a number of JavaBeans naming
conventions.
Introspector

can determine the list of properties supported by a bean, for
example, by scanning the class for methods that have the right names and signatures to be
get

and
set

property accessor methods.

The introspection mechanism does not rely on the reflection capabilities of Java
alone, however. Any bean can define an auxiliary
BeanInfo

class that provides additional
information about the bean and its properties, events, and methods. The
Introspector

a
utomatically attempts to locate and load the
BeanInfo

class of a bean.

The
BeanInfo

class provides additional information about the bean primarily in
the form of
FeatureDescriptor

objects, each one describing a single feature of the
bean. Each
FeatureDesc
riptor

provides a name and brief description of the feature it
documents. The beanbox tool can display the name and description to the user, making
the bean essentially self
-
documenting and easier to use. Specific bean features, such as
properties, events,

and methods, are described by specific subclasses of
FeatureDescriptor
, such as
PropertyDescriptor
,
EventSetDescriptor
, and
MethodDescriptor
.

One of the primary tasks of a beanbox application is to allow the user to
customize a bean by setting property v
alues. A beanbox defines
property editors

for
commonly used property types, such as numbers, strings, fonts, and colors. If a bean has
a property of a more complicated type, however, it can define a
PropertyEditor

class
that enables the beanbox to let the
user set values for that property.

The introspection facilities in the JavaBeans API define the mechanism by which
components make their internal structure readily available to the outside world. These
facilities consist of the functional overhead necessa
ry to enable development tools to
query a bean for its internal structure, including the interfaces, methods, and member
variables that comprise the bean. Although the introspection services are primarily
designed for use by application builder tools, they

are grouped separately from the

16

application builder services in the API because their role in making a bean's internal
structure available externally is technically independent of builder tools. In other words,
there might be other reasons for querying a
bean as to its internal structure beyond the
obvious use in builder tools.

The introspection services provided by the JavaBeans API are divided into two
parts, low
-
level services and high
-
level services, which are distinguished by the level of
access they
provide to bean internals. The low
-
level API services are responsible for
enabling wide access to the structural internals of a bean. These services are very
important for application builder tools that heavily use bean internals to provide advanced
develo
pment features. However, this level of access isn't appropriate for developers who
are using beans to build applications because it exposes private parts of a bean that aren't
meant to be used by developers at the application level. For these purposes, the

high
-
level
API services are more appropriate.

The high
-
level services use the low
-
level services behind the scenes to provide
access to limited portions of a bean's internals, which typically consist of a bean's public
properties and methods. The differen
ce between the two levels of services is that the
high
-
level services don't enable access to internal aspects of a bean that aren't specifically
designed for external use. The end result is two distinct services that offer bean
introspection capabilities b
ased on the level of access required by the interested party, be
it an application builder tool or a user.

By using a
BeanInfo

class, you can expose subsets of a particular Bean feature.
For example, by not returning a method descriptor for a particular me
thod, that method
will not be exposed in a builder tool.

When you use a
BeanInfo

class:



Base class features will
not

be exposed. You can retrieve base class
features by using the
BeanInfo.getAdditionalBeanInfo

method.



Properties, events, or methods that

have no descriptor will
not

be exposed.
For a particular feature, only those items returned in the descriptor array

17

will be exposed. For example, if you return descriptors for all your Bean
methods except
foo
, then
foo

will not be exposed.



Low
-
level refl
ection will be used for features with getter methods
returning null. For example if your
BeanInfo

class contains this method
implementation:

public MethodDescriptor[] getMethodDescriptors() {


return null;

}

Then low
-
level reflection will be used to di
scover your Bean's
public methods.

Here are the classes and interfaces that make up the introspection portion of the
JavaBeans API:



BeanDescriptor




EventSetDescripto




FeatureDescripto




IndexedPropertyDescripto




IntrospectionExceptio




Introspecto




MethodD
escripto




ParameterDescripto




PropertyDescripto




SimpleBeanInf




BeanInf


BeanDescriptor

The
BeanDescriptor

class provides global information about a bean, including the name
of the bean and the bean's customizer. You learn about customizers in Chapter 8,
"
Customization: Bean Support for Application Builders."

EventSetDescriptor


18

The
EventSetDescriptor

class represents a set of events that a bean is capable of
generating. The events defined in an
EventSetDescriptor

class are all deliverable as
method calls o
n a single event listener interface.

FeatureDescriptor

The
FeatureDescriptor

class serves as a common base class for the
EventSetDescriptor
,
MethodDescriptor
, and
PropertyDescriptor

classes. It
represents bean information that is common across these class
es, such as the name of an
event, method, or property.

IndexedPropertyDescriptor

The
IndexedPropertyDescriptor

class represents a publicly accessible indexed
property. This class provides methods for accessing the type of an indexed property along
with it
s accessor methods.

IntrospectionException

The
IntrospectionException

class is used to bring attention to an error that has
occurred during introspection, such as an accessor method with an invalid type signature.

Introspector

The
Introspector

class prov
ides the overhead necessary to analyze a bean and
determine its public properties, methods, and events. This class uses explicit bean
information if it exists, and it relies on reflection and design patterns to automatically
analyze a bean if not.

MethodD
escriptor

The
MethodDescriptor

class represents a publicly accessible method. This class
provides methods for accessing information such as a method's parameters.

ParameterDescriptor


19

The
ParameterDescriptor

class represents the parameters to a method and
is mainly
provided as a means for bean developers to provide detailed parameter information
beyond that obtained through the Java reflection services.

PropertyDescriptor

The
PropertyDescriptor

class represents a publicly accessed property. This class
prov
ides methods for accessing the type of a property along with its accessor methods
and whether it is bound or constrained.

SimpleBeanInfo

The
SimpleBeanInfo

class is a support class designed to make it easier for bean
developers to provide explicit informa
tion about a bean. This class basically implements
every method in the
BeanInfo

interface but returns a value that triggers the automatic
introspection services. This enables developers to provide selective bean information by
overriding specific methods,
without having to implement every method in the
BeanInfo

interface.

BeanInfo

The
BeanInfo

interface defines a set of methods that can be used to find out information
explicitly provided by a bean, such as lists of properties, methods, and events. Develope
rs
who want to provide explicit bean information must implement the
BeanInfo

interface
and provide suitable information. It's important to note that any information not explicitly
provided via the
BeanInfo

interface is determined using the automatic intros
pection
facilities of the JavaBeans API.

Locating BeanInfo Classes

Before examining a Bean, the
Introspector

will attempt to find a
BeanInfo

class associated with the Bean. By default, the
Introspector

takes the target Bean's
fully qualified package name,

and appends "BeanInfo" to form a new class name. For

20

example, if the target Bean is
sunw.demo.buttons.ExplicitButton
, then the
Introspector

will attempt to locate
sunw.demo.buttons.ExplicitButtonBeanInfo
.

If that fails, then each package in the
BeanInfo

search path is searched. The
BeanInfo

search path is maintained by
Introspector.setBeanInfoSearchPath()

and
Introspector.getBeanInfoSearchPath()
.

Customization


Customization

allows a user to alter the appearance and behavior of a bean. A
complex bean may

not be satisfied with the property
-
by
-
property customization
mechanism provided by most beanbox tools. Such a bean can define a
Customizer

class
to create a graphical interface that allows the user to configure a bean in some useful
way. A particularly co
mplex bean can even define customizers that serve as "wizards"
that guide the user step by step through the customization process. To define a
customizer, or wizard, for configuring a bean
B
, define an AWT or Swing component
with a no
-
parameter constructor

that does the customization. The class is commonly
called
B
Customizer
, but this is not required. Register the class with the
BeanDescriptor

object returned by the
BeanInfo

class for the bean.

The real motive behind bean customization is that of making app
lication
development easier and smoother through the use of reusable beans with visual
application builder tools. If you don't quite see the significance of customization in this
light, contrast how a bean is used as opposed to a traditional Java class. A
traditional Java
class is always used in a programmatic fashion, meaning that Java code must be written
to create and interact with it. Furthermore, programmers must study a traditional class's
API to figure out how to use the class. This is assuming the c
lass ships with a well
-
documented API, which isn't always the case. The point is that Java classes are always
used at the code level, which limits their usability to developers with a fair degree of
programming knowledge.

Now consider the case of a bean. B
eans can be used in all the same ways as Java
classes, and they also can be used as visual building blocks in application builder tools.

21

When used in an application builder tool, beans are selected and laid out graphically by
the user, with their propertie
s and events exposed for editing entirely through visual
interfaces. The ability to build applications visually lessens the technical expertise
necessary to partake in application development. In other words, JavaBeans
customization helps bring application

development to a less technical crowd because of
its support for visual bean editing.

In addition, a complex bean may not be satisfied with the property
-
by
-
property
customization mechanism provided by most beanbox tools. Such a bean can define a
Customize
r

class to create a graphical interface that allows the user to configure a bean
in some useful way. A particularly complex bean can even define customizers that serve
as "wizards" that guide the user step by step through the customization process.

A
bean

context

is a logical container (and often a visual container) for JavaBeans
and, optionally, for other nested bean contexts. In practice, most JavaBeans are AWT or
Swing components or containers. Beanbox tools recognize this and allow component
beans to b
e nested within container beans. A bean context is a kind of heavyweight
container that formalizes this nesting relationship. More importantly, however, a bean
context can provide a set of services (e.g., printing services, debugging services, database
con
nection services) to the beans it contains. Beans that are aware of their context can be
written to query the context and take advantage of the services that are available. Bean
contexts are implemented using the
java.beans.beancontext

API, which is new as

of
Java 1.2.

A Bean's appearance and behavior can be customized at design time within Beans
-
compliant builder tools. Typically there are two ways to customize a Bean:



By using a
property editor
. Each Bean property has its own
property editor. A builder t
ool usually displays a Bean's
property editors in a
property sheet
. A property editor is
associated with, and edits a particular property type.



By using
customizers
. Customizers give you complete GUI
control over Bean customization. Customizers are used w
here

22

property editors are not practical or applicable. Unlike a
property editor, which is associated with a property, a
customizer is associated with a Bean.

Developers are free to create their own custom property sheets and editors
for use with their com
ponents if the defaults aren't appropriate for a particular
component. It's possible to create elaborate property editors for changing the
value of specific properties, as well as create sophisticated property sheets to
house those editors.

Imagine that yo
u have created a
Sound

class that is capable of playing
various sound format files. You could create a custom property editor for this
class that listed all of the known system sounds in a list. The JavaBeans
architecture also allows you to associate a cus
tom editor with your component. If
the task of setting the property values and behaviors of your component is
complicated, it may be useful to create a component wizard that guides the user
through the steps. The size and complexity of your component edito
r is entirely
up to you.

The application builder tool support in JavaBeans begins with property
editors, which are visual interfaces for editing a particular type of property.
Property editors form the basis of bean customization because they are
implement
ed at the property level, which facilitates reusing them in more
comprehensive scenarios such as property sheets and customizers. Don't worry,
you learn about property sheets and customizers a little later in this chapter in the
"Property Sheets" and "Cust
omizers" sections.

The aim of property editors is to enable you to add visual editing
capabilities to every conceivable bean property type. With each property type
having a corresponding editor, it then becomes possible to edit entire beans
simply as a gro
up of properties. JavaBeans provides property editors for built
-
in
Java data types such as integers, booleans, and strings.

Although property editors are very useful at the property level, the editing of
properties always takes place within the context of

a complete bean. In other words,

23

editing a bean usually involves interacting with a group of property editors because beans
usually contain multiple properties. To facilitate the editing of complete beans,
JavaBeans provides property sheets, which are vis
ual interfaces that consist of all the
property editors necessary to edit the public properties of a bean. Property sheets are
usually implemented as dialog boxes that contain a variety of different individual
property editors, depending on the specific pr
operties within a bean.

Bean customizers are more elaborate visual interfaces that enable you to edit
beans in a hopefully more intuitive fashion. Customizers are similar to property sheets in
that they enable you to edit a complete bean, but they differ i
n that they take on a totally
different approach to presenting the individual property editors. Most customizers act like
wizards, which are visual editors that gather property information in a multiple
-
step
process. The purpose of offering this route to b
ean editing is to give bean developers the
freedom to implement more intuitive visual interfaces.

Customizers often attempt to provide editing facilities within the context of a
series of questions. By presenting property information in the form of questio
ns, the task
of customizing a bean is made much simpler. Of course, for simple beans customizers are
probably overkill; they are primarily useful for beans that would be complex to edit using
normal property sheets. Keep in mind that customizers are design
ed and implemented
entirely by bean developers. JavaBeans supports the use of customizers, but it doesn't go
much further than that. All JavaBeans really provides is an interface,
Customizer
, that
must be implemented by customizers. In other words, buildin
g a customizer for a bean
can involve a significant amount of work on the developer's part. On the other hand, a
powerful customizer interface can make a bean infinitely more useful to the end user, so
it's often worth the extra development effort.

Proper
tyEditorManager

The
PropertyEditorManager

class is used to locate the property editor for a
property of a given type. Property editors capable of being located by the
PropertyEditorManager

class must implement the
PropertyEditor

interface. The

24

PropertyEdit
orManager

class provides a means of registering property types so that
their editors can be easily found. For property types that haven't been registered, the
PropertyEditorManager

class looks for property editors using the name of the property
with
Editor

appended to the end.

PropertyEditorSupport

The
PropertyEditorSupport

class is a helper class implementing the
PropertyEditor

interface that is used to make the construction of custom property
editors a little easier.

Customizer

The
Customizer

interface
defines the overhead required to provide a complete
visual editor for a bean. Classes implementing the
Customizer

interface are typically
derived from the
Component

class so that they can be used within the context of a dialog
box or panel.

PropertyEditor

The
PropertyEditor

interface defines a means of visually editing a single bean
property of a given type. Because JavaBeans provides standard property editors for built
-
in data types, you are only required to develop property editors for custom data types.

The
PropertyEditor

interface provides a couple of different options in regard to editing
a property. It is up to bean developers which specific type of editing they want to provide
via the
PropertyEditor

interface.

Persistence

Persistence is the mechanis
m by which beans are stored away in a nonvolatile
place for later use. This statement, as straightforward as it is, might not give you the full
picture as to what persistence means to JavaBeans. When you think about the concept of
persistence, you have to
consider the issue of a bean's life cycle. In other words, in the
absence of persistence, consider what the lifetime of a bean consists of. To start things

25

off, a bean first is created, probably within the context of some application or application
builder

tool. Then, some properties are probably manipulated and some public methods
called on the bean. After seeing some degree of use, the bean will eventually no longer be
needed and will be destroyed (removed from memory), never to be seen or heard from
agai
n.

Without persistence, a bean's life cycle is limited to whatever happens in the
context of a particular session of an application. When an application ends, all the beans
that have been created alongside it are automatically destroyed. You might be thin
king
that this is no big deal, considering the fact that beans are just little objects and can easily
be re
-
created. But remember that a significant part of using beans is being able to
customize them for use in different situations. And what good are cust
omized beans if the
customizations are lost after you close an application? Persistence puts a twist on the life
cycle of a bean by providing a means to keep up with the state of a bean and restore it
later.

Serialization

Persistence in JavaBeans is tightl
y linked to a feature of the core Java API: object
serialization. Serialization is the process of reading or writing an object to

a stream of data. The Java object serialization facilities define a consistent

format for reading and writing Java objects t
o a stream of bytes suitable for storage in a
file. This serialization support provides a complete solution for storing and retrieving
Java objects to nonvolatile locations, such as files. One of the ways in which JavaBeans
uses serialization is in its aut
omatic approach to persistence, which involves storing and
retrieving a bean based on its properties.

The key to storing and retrieving an object in this manner is representing the state
of the object in a serialized form sufficient to reconstruct the obje
ct. In other words, the
format used to store an object must sufficiently describe the object so it can be later
reconstructed to the same state. From the perspective of JavaBeans, it isn't terribly
important exactly how a bean is resolved into bytes, as lo
ng as it can be completely
restored.


26

The serialization functionality provided by the standard Java API has the
following qualities, which help make it an ideal persistence solution for JavaBeans:



Simple, yet extensible serialization mechanism



Maintains
object types and properties within the serialized format



Is extensible enough to support remote objects



Requires additional overhead only for customization



Enables objects to define their own external formats through
customization

At this point, you mi
ght be starting to realize that in terms of JavaBeans,
persistence and serialization mean practically the same thing. This is because JavaBeans
persistence is implemented entirely through the serialization facilities provided by the
core Java API. Although

this might seem like the JavaBeans architects were avoiding
some work, the truth is that using the standard Java serialization mechanism helps
JavaBeans maintain more consistency with Java itself. The end result is that developers
who understand serializa
tion in terms of Java will also be able to work with serialization
in JavaBeans without having to learn anything new. This is a good example of code reuse
and how important it is to Java and related technologies such as JavaBeans.