Introduction to java beans, java beans, Core java, j2se, getting started with java beans programming, java to standard edition, beans in java, beans programming in java
3. ADVANCE JAVA
Author Profile
Ankit Desai
Ph.D. Scholar, IET, Ahmedabad University
Education: M. Tech. (C.E.), B. E. (I. T.)
Experience: 8 years (Academic and Research)
Research Interest: IoT, Big Data Analytics, Machine
Learning, Data Mining, Algorithms.
Classified e-Material 3
5. Advanced Java
Classified e-Material 5/17
JavaBean Concepts
JavaBeans™ is a portable, platform-independent
component model written in the Java programming
language.
JavaBean components are known as beans
With the JavaBeans API you can create reuseable,
platform-independent components.
Through the design mode of a builder tool, you use the
property sheet or bean customize to customize the bean
and then save (persist) your customized beans.
6. Advanced Java
Classified e-Material 6/17
Key bean concepts
Builder tools
discover a bean's features (that is, its properties,
methods, and events) by a process known as
introspection.
Properties are the appearance and behavior
characteristics of a bean
Beans use events to communicate with other beans.
Listener Bean – That receives event call
Source Bean - That fires event call
Persistence enables beans to save and restore their
state.
7. Advanced Java
Classified e-Material 7/17
Writing a Simple Bean
This section covers the following actions:
Creating a simple bean
Compiling the bean
Inspecting the bean's properties and events
8. Advanced Java
Classified e-Material 8/17
TO create a simple bean first open new file and save it as
simpleBean.java
Place the following code in that file
import java.io.Serializable;
public class MyBean implements java.io.Serializable
{
protected int theValue;
public MyBean(){ }
public void setMyValue(int newValue)
{
theValue = newValue;
}
public int getMyValue()
{
return theValue;
}
}
9. Advanced Java
Classified e-Material 9/17
SimpleBean extends the javax.swing.JLabel graphic
component and inherits its properties, which makes the
SimpleBean a visual component.
Inspect Properties and Events of simpleBean.java
Following are the properties
theValue
And events to set that properties
settheValue();
gettheValue();
10. Advanced Java
Classified e-Material 10/17
More on Bean Properties
The JavaBeans™ specification defines the following types
of bean properties:
Simple Properties
with a single value whose changes are independent of
changes in any other property.
Bound Properties
for which a change to the property results in a
notification being sent to some other bean.
Constrained Properties
for which a change to the property results in
validation by another bean. The other bean may
reject the change if it is not appropriate
Indexed Properties
that supports a range of values instead of a single
value.
11. Advanced Java
Classified e-Material 11/17
Bean properties can also be classified as follows:
Writable – A bean property that can be changed
Standard
Expert
Preferred
Read Only – A bean property that cannot be changed.
Hidden – A bean property that can be changed. However,
these properties are not disclosed with the BeanInfo
class
12. Advanced Java
Classified e-Material 12/17
Simple Properties
Simple properties can be accessed just by accessor
methods of java beans
Normally two accessor methods available known as
getter methods
responsible for reading a bean's properties
setter methods
responsible for writing a beans properties
getter and setter methods form the interface between
a bean's properties and the outside world
Following is an example of simple property and its
acccessor method
13. Advanced Java
Classified e-Material 13/17
Simple Bean Property Example
public class MyBean
{
public MyBean() { }
private String title;
public String getTitle()
{
return this.title;
}
public void setTitle(String title)
{
this.title = title;
}
Creates a new instance of MyBean
Holds Value of Property ‘Title’
Getter Property for ‘title’
Setter Property for ‘title’
14. Advanced Java
Classified e-Material 14/17
Bound Properties
Bound properties provide a notification service upon
being changed.
The accessor methods for a bound property are defined
in the same way as those for simple properties
However a bean with a bound property is required to fire
a PropertyChange method of the PropertyChangeListener
objects. This is illustrated in following figure
16. Advanced Java
Classified e-Material 16/17
Implementing Bound Property
Import the java.beans package. This gives you access to
the PropertyChangeSupport class.
Instantiate a PropertyChangeSupport object. This object
maintains the property change listener list and fires
property change events. You can also make your class a
PropertyChangeSupport subclass.
Implement methods to maintain the property change
listener list.
Modify a property's set method to fire a property change
event when the property is changed.
17. Advanced Java
Classified e-Material 17/17
java.beans.PropertyChangeEvent class
public class java.beans.PropertyChangeEvent extends
java.util.EventObject
{
PropertyChangeEvent(Object source,
String propertyName,
Object oldValue,
Object newValue);
public Object getNewValue();
public Object getOldValue();
public Object getPropagationId();
public String getPropertyName();
public void setPropagationId();
}
Constructor
Source of Event
Name of property
Old Value
New Value
18. Advanced Java
Classified e-Material 18/17
Constrained Properties
For which a change to the property results in validation
by another bean.
The other bean may reject the change if it is not
appropriate.
Properties that go through this approval process are
known as constrained properties.
They differ from other kind of properties in a way that
setter method of constrained properties throws the
java.beans.PropertyVetoException
19. Advanced Java
Classified e-Material 19/17
Implementing Constrained Property
Those objects that want to participate in the approval
process for a change to a constrained property must
implement the java.beans.VetoableChangeListener
interface.
This interface contains a method called
vetoableChange() that takes a single parameter of type
PropertyChangeEvent.
This method may throw the
java.beans.PropertyVetoException
if it wants to reject the change.
This Process is shown in following figure
20. Advanced Java
Classified e-Material 20/17
It's possible for the object that owns the property to reject a
change itself.
So if a setPropertyName() method is called with an
unacceptable property value, the
java.beans.PropertyVetoException
can be thrown.
If the owning object does not reject the change, it must send
notifications to all registered VetoableChangeListener objects.
This gives any VetoableChangeListener a chance to reject the
change to property
The event source must catch the
java.beans.PropertyVetoException.
21. Advanced Java
Classified e-Material 21/17
Property Owner
setProperty()
vetoebleChangeListnersvetoebleChangeListnersvetoebleChangeListnersvetoebleChangeListners
vetoebleChang()
Throw
propertyVetoException
if Change is required
Throw
propertyVetoException
if Change is required
22. Advanced Java
Classified e-Material 22/17
java.beans.VetoableChangeSupport
public class java.beans.VetoableChangeSupport
implements java.io.Serializable
{
public VetoableChangeSupport(Object source);
public synchronized void
addVetoableChangeListener(VetoableChangeListener l);
public void fireVetoableChange(String propertyName, Object
oldValue, Object newValue) throws
java.beans.PropertyVetoException;
public synchronized void
removeVetoableChangeListener(VetoableChangeListener l);
}
construct the object
add a vetoablechangelistener
Fire vetoable change event to any Listner
remove a vetoablechangelistener
23. Advanced Java
Classified e-Material 23/17
Indexed Properties
An indexed property is an array of properties or objects
that supports a range of values and enables the accessor
to specify an element of a property to read or write .
Indexed properties are very similar to arrays in
traditional Java programming.
Indexed properties contain several elements of the same
type that can be accessed via an integer index.
Hence the name indexed property
24. Advanced Java
Classified e-Material 24/17
Indexed properties has multiple values so the standard
getter and setter methods aren't sufficient
So there available two pairs of accessor methods
One pair gets and sets individual properties in the
array via an index. For example :
public PropertyType[] getProperty();
public void setProperty(PropertyType[] value);
While the other pair gets and sets the entire array of
properties as a single unit
public PropertyType getProperty(int index);
public void setProperty(int index, PropertyType
value);
25. Advanced Java
Classified e-Material 25/17
Just as in working with standard Java arrays, it is
possible to index outside the bounds of an indexed
property array.
When this occurs, the accessor method used to perform
the indexing typically throws an
java.lang.ArrayIndexOutOfBoundsException
runtime exception,
which is consistent with how normal Java arrays behave
when indexed out of bounds.
26. Advanced Java
Classified e-Material 26/17
Manipulating Events
Event passing is the means by which components
communicate with each other.
The event model by the JavaBeans architecture is
composed of three main parts:
sources,
events
listeners.
The source of an event is the object that originates or
fires the event.
The source must define the events it will fire,
as well as the methods for registering listeners of
27. Advanced Java
Classified e-Material 27/17
Topics in events Handling
You learn the following major issues in this chapter:
Event basics
Event state objects
Event listeners
Event sources
Event adapters
Delivering events
28. Advanced Java
Classified e-Material 28/17
Event Basics
The event-handling mechanism is directly based on the
built-in event-handling facilities provided by the Java API
Event sources are capable of generating events
Event listeners are designed to respond to events.
An event is propagated from an event source to an event
listener when the event source invokes a method on the
listener.
Beans typically play the role of event sources
29. Advanced Java
Classified e-Material 29/17
This figure illustrate the basics of events
Event Source
Event ListenerFire Events
Register Event
Listener
Event
Object
30. Advanced Java
Classified e-Material 30/17
Event State Object
An event object (or event state object) encapsulates the
information that is specific to an instance of an event.
For example, an event that represents a mouse click
might contain the position of the mouse pointer
This object is passed as the parameter to an event
notification method.
The class java.util.EventObject is used as the base class
for all event objects. It has following events
31. Advanced Java
Classified e-Material 31/17
java.util.EventObject methods
Methods Description
public EventObject(Object
source)
The constructor for the event.
public Object getSource() Returns the object that generated
the event.
public String toString() Renders the event object in
human-readable form.
32. Advanced Java
Classified e-Material 32/17
Event Listener
An event listener is an object that needs to be notified
when certain events occur.
Event notifications are made through method invocations
on the listening object.
But in order to fire an event, the event source must
know what listener method to call.
This information is contained in an event-listener
interface that defines the methods called to fire an event
notification.
Any class that wants to receive notifications of the event
would implement that interface.
33. Advanced Java
Classified e-Material 33/17
All event-listener interfaces inherit from the base
interface
java.util.EventListener.
By convention, all event-listener interfaces have names
ending in the word
Listener.
An event-listener interface can contain any number of
methods, each one corresponding to a different event.
34. Advanced Java
Classified e-Material 34/17
The methods that are defined in the event-listener
interfaces should conform to the standard design pattern
for event notification methods.As below..
void eventOccurenceMethodName (EventObjectType evt);
The eventOoccurrenceMethodName should describe
the event.
The EventObjectType is passed when the event is
fired.
And this object must be derived from the class
java.util.EventObject.
35. Advanced Java
Classified e-Material 35/17
Event sources are objects that fire events.
Event sources must provide a means for registering
listeners.
Sources are required to implement a pair of registration
methods for each type of event listener they support.
The standard design pattern for event-listener registratio
is as below
public void addListenerType( ListenerType listener);
public void removeListenerType( ListenerType listener);
Event Sources
36. Advanced Java
Classified e-Material 36/17
The above pattern identifies the object that implements
these methods as an event source for the eventlistener
interface of type ListenerType.
The client object invokes the addListenerType method
to register an interest in the events supported by the
associated interface.
When the client object is no longer interested in
receiving these event notifications it invokes the
corresponding removeListenerType method.
Multiple listeners can also be registered with a source for
a given set of events. This is called multicast event
delivery.
37. Advanced Java
Classified e-Material 37/17
Event adapters
While using multicast event delivery as described earlier we
may face problems like..
If a given object wanted to listen for events from a large
number of event source objects, it would have to implement
the interfaces for every one.
This may not be the best approach If only a few of the
events that are supported by the event listener interfaces
are of interest.
Another problem occurs when an object is listening for events
from two or more objects that are sources of the same event
types.
Since an object can only implement an event listener
interface once, it would have to figure out for itself which
object was the source of the event.
38. Advanced Java
Classified e-Material 38/17
These problems can (and often will) lead to code that is
hard to read and even harder to maintain.
To deal with this is to introduce another object—
an event adapter—between the event source and the
event target.
The purpose of this object is to adapt the source to the
specific needs of the target.
Following figure shows object interaction using an
adapter
40. Advanced Java
Classified e-Material 40/17
Event Adapter Classes
The following are some event adapter classes provided
by the Java API:
FocusAdapte
KeyAdapte
MouseAdapte
MouseMotionAdapte
WindowAdapte
41. Advanced Java
Classified e-Material 41/17
Delivering Events
An event delivery consists of three functional parts:
An event source
An event listener
An event state object .
Entire process begins when an event listener notifies a
source that it wants to listen to a particular event.
It does this by calling an event listener registration
method provided by the source.
42. Advanced Java
Classified e-Material 42/17
When this happens, the source is ready to deliver events
to the listener.
Whenever an internal change occurs in the source that
generates an event, the source creates an event state
object describing the event and sends it out to the
listener.
The source does this by calling one of the event
response methods defined in the listener's event listener
interface.
43. Advanced Java
Classified e-Material 43/17
Multicast event Delivery
Multiple event listeners can be registered with and
receive events from a single event source, this type of
event delivery is known as multicast delivery.
With multicast event delivery, event listeners can be
added and removed at will via the event listener
registration methods.
The source is responsible for keeping track of the current
set of listeners.
Java event delivery mechanism makes no guarantees
about the order in which listeners receive events during
a multicast delivery.
44. Advanced Java
Classified e-Material 44/17
Unicast Event Delivery
In Unicast event delivery, only one listener is permitted
to listen to a source at a time.
Unicast event sources can have only one registered
listener at any given time.
The event registration methods are designed so that an
exception is thrown if additional listeners are attempted
to be added to a unicast event source with a listener
already registered.
It's important to understand that unicast event delivery
is a more limited form of event delivery and should be
avoided whenever possible
45. Advanced Java
Classified e-Material 45/17
Problems in Event Delivery
When event response methods throw exceptions back at
an event source
The problem is, how should an event source react to
an event response method when the listener throws
an exception?
Unfortunately, there are no hard and fast rules
governing what should happen in a situation like this.
It is entirely implementation specific, so you might
want to refer to the source documentation if you are
worried about this problem creeping up on you
46. Advanced Java
Classified e-Material 46/17
when the set of event listeners for a source is updated
during a multicast event delivery.
In this situation it is technically possible for a listener
to be removed from the source before its event has
been delivered.
When this occurs, it is possible for an event to be
delivered to a listener that is no longer registered,
Again, there unfortunately are no strict rules about
how event sources should deal with this scenario.
47. Advanced Java
Classified e-Material 47/17
Bean Persistence
It’s a mechanism that enables the state of components
to be stored in a non-volatile place for later retrieval.
The mechanism that makes persistence possible is called
serialization.
Object serialization means converting an object into a
data stream and writing it to storage
To support persistance beans must support serialization
by implementing
java.io.Serializable
java.io.Externalizable
48. Advanced Java
Classified e-Material 48/17
Controlling Serialization
Three ways to control serialization :
Automatic serialization, implemented by the Serializable
interface.
Customized serialization. Selectively exclude fields you
do not want serialized
Customized file format, implemented by the
Externalizable interface and its two methods.
49. Advanced Java
Classified e-Material 49/17
Default Serialization: The Serializable Interface
The Serializable interface provides automatic
serialization by using the Java Object Serialization tools.
Serializable declares no methods
Important points about working with the Serializable
Classes that implement Serializable must have an
access to a no-argument constructor of supertype.
Don't implement Serializable in your class if it is
already implemented in a superclass.
All fields except static and transient fields are
serialized.
50. Advanced Java
Classified e-Material 50/17
Selective Serialization Using the transient Keyword
To exclude fields from serialization in a Serializable
object from serialization, mark the fields with the
transient modifier.
transient int status;
Default serialization will not serialize transient and static
fields
51. Advanced Java
Classified e-Material 51/17
Selective Serialization: writeObject and readObject
If your serializable class contains either of the following
two methods ,then the default serialization will not take
place.
private void writeObject (java.io.ObjectOutputStream out)
throws IOException;
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
You can control how more complex objects are serialized,
by writing your own implementations of the writeObject
and readObject methods.
52. Advanced Java
Classified e-Material 52/17
The Externalizable Interface
Use the Externalizable interface when you need complete
control over your bean's serialization
for example, when writing and reading a specific file
format.
To use the Externalizable interface you need to
implement two methods:
readExternal
writeExternal
Classes that implement Externalizable must have a no-
argument constructor.
53. Advanced Java
Classified e-Material 53/17
Introspection
Introspection is the automatic process of analyzing a
bean's design patterns to reveal the bean's properties,
events, and methods.
This process controls the publishing and discovery of
bean operations and properties.
Following are the topics to be covered
The purpose of introspection,
Introduces the Introspection API,
An example of introspection code.
54. Advanced Java
Classified e-Material 54/17
The purpose of introspection
Introspection provides a great advantages:
Portability - Everything is done in the Java platform
so there are no platform-specific issues
Reuse – Component Reuse potential possibly exceeds
your expectations.
By following the JavaBeans design conventions,
Implementing the appropriate interfaces,
Extending the appropriate classes,
55. Advanced Java
Classified e-Material 55/17
Introspection API
The JavaBeans API architecture supplies a set of classes
and interfaces to provide introspection.
The BeanInfo interface of the java.beans package
defines a set of methods that allow bean implementors
to provide explicit information about their beans.
The getBeanInfo(beanName) of the Introspector class
can be used by automated environments to provide
detailed information about a bean.
The Introspector class provides descriptor classes with
information about properties, events, and methods of a
bean.
56. Advanced Java
Classified e-Material 56/17
A hierarchy of the FeatureDescriptor classes
FeatureDescriptor
FeatureDescriptor
FeatureDescriptor
FeatureDescriptor
FeatureDescriptor
FeatureDescriptor
IndexedPropertyDescriptor
57. Advanced Java
Classified e-Material 57/17
An example of introspection code.
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
public class SimpleBean
{
private final String name = "SimpleBean";
private int size;
58. Advanced Java
Classified e-Material 58/17
Getter and setter Methods for Properties
public String getName()
{
return this.name;
}
public int getSize()
{
return this.size;
}
public void setSize( int size )
{
this.size = size;
}
59. Advanced Java
Classified e-Material 59/17
Main() Method to check beans
public static void main( String[] args ) throws
IntrospectionException
{
BeanInfo info = Introspector.getBeanInfo(
SimpleBean.class );
for ( PropertyDescriptor pd :
info.getPropertyDescriptors() )
System.out.println( pd.getName() );
}
}
60. Advanced Java
Classified e-Material 60/17
Summary
It is a public class.
It has a public parameterless constructor (though it
may have other constructors as well)
It implements Serializable interface
It has properties with “getter” and “setter” methods
It has events which follow the standard Java event
model with the registration methods