SlideShare uma empresa Scribd logo
1 de 60
ADAVANCE JAVA
JavaBeans
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
Advanced Java
Classified e-Material 4/17
Agenda
 JavaBeans Concepts
 Writing a Simple Bean
 Bean Properties
 Manipulating Events
 Bean Persistence
 Introspection
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.
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.
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
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;
}
}
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();
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.
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
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
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’
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
Advanced Java
Classified e-Material 15/17
Property Owner
Property 1
Property 2
Property n
PropertyChangeListner
PropertyChange()
Method
Property 1
changed
Property 2
changed
Property n
changed
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.
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
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
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
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.
Advanced Java
Classified e-Material 21/17
Property Owner
setProperty()
vetoebleChangeListnersvetoebleChangeListnersvetoebleChangeListnersvetoebleChangeListners
vetoebleChang()
Throw
propertyVetoException
if Change is required
Throw
propertyVetoException
if Change is required
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
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
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);
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.
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
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
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
Advanced Java
Classified e-Material 29/17
 This figure illustrate the basics of events
Event Source
Event ListenerFire Events
Register Event
Listener
Event
Object
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
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.
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.
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.
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.
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
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.
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.
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
Advanced Java
Classified e-Material 39/17
Event Source
Event Adapter
Event Listener
Register
Event Listener
Event
Object
Fire Event
Provide interface
Forward event
Event
Object
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
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.
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.
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.
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
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
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.
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
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.
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.
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
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.
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.
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.
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,
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.
Advanced Java
Classified e-Material 56/17
A hierarchy of the FeatureDescriptor classes
FeatureDescriptor
FeatureDescriptor
FeatureDescriptor
FeatureDescriptor
FeatureDescriptor
FeatureDescriptor
IndexedPropertyDescriptor
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;
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;
}
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() );
}
}
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

Mais conteúdo relacionado

Mais procurados (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Interface
InterfaceInterface
Interface
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
 
Java package
Java packageJava package
Java package
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Java awt
Java awtJava awt
Java awt
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Java swing
Java swingJava swing
Java swing
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
OOP java
OOP javaOOP java
OOP java
 

Destaque (20)

Javabeans
JavabeansJavabeans
Javabeans
 
Java beans
Java beansJava beans
Java beans
 
Java beans
Java beansJava beans
Java beans
 
Bean Intro
Bean IntroBean Intro
Bean Intro
 
javabeans
javabeansjavabeans
javabeans
 
Java bean
Java beanJava bean
Java bean
 
Java beans
Java beansJava beans
Java beans
 
introduction of Java beans
introduction of Java beansintroduction of Java beans
introduction of Java beans
 
java code and document security
java code and document securityjava code and document security
java code and document security
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Java beans
Java beansJava beans
Java beans
 
java Jdbc
java Jdbc java Jdbc
java Jdbc
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
 
Java beans
Java beansJava beans
Java beans
 
Presentation11 sq lite
Presentation11 sq litePresentation11 sq lite
Presentation11 sq lite
 
Presentation14 audio play
Presentation14 audio playPresentation14 audio play
Presentation14 audio play
 
Presentation4 date picker
Presentation4 date pickerPresentation4 date picker
Presentation4 date picker
 
Presentation8 silder switch_progress
Presentation8 silder switch_progressPresentation8 silder switch_progress
Presentation8 silder switch_progress
 
Presentation15 parse xml
Presentation15 parse xmlPresentation15 parse xml
Presentation15 parse xml
 
Hadoop installation
Hadoop installationHadoop installation
Hadoop installation
 

Semelhante a Java Beans

Semelhante a Java Beans (20)

Java Beans Unit 4(Part 1)
Java Beans Unit 4(Part 1)Java Beans Unit 4(Part 1)
Java Beans Unit 4(Part 1)
 
Advance java session 12
Advance java session 12Advance java session 12
Advance java session 12
 
Java EE and Glassfish
Java EE and GlassfishJava EE and Glassfish
Java EE and Glassfish
 
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
 
Using java beans(ii)
Using java beans(ii)Using java beans(ii)
Using java beans(ii)
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Vaadin JPAContainer
Vaadin JPAContainerVaadin JPAContainer
Vaadin JPAContainer
 
13 java beans
13 java beans13 java beans
13 java beans
 
Java beans
Java beansJava beans
Java beans
 
Javabean1
Javabean1Javabean1
Javabean1
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Java beans
Java beansJava beans
Java beans
 
Constructor in Java - ITVoyagers
Constructor in Java - ITVoyagersConstructor in Java - ITVoyagers
Constructor in Java - ITVoyagers
 
P20CSP105-AdvJavaProg.pptx
P20CSP105-AdvJavaProg.pptxP20CSP105-AdvJavaProg.pptx
P20CSP105-AdvJavaProg.pptx
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
Jsp
JspJsp
Jsp
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
 

Mais de Ankit Desai

java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transferAnkit Desai
 
java swing programming
java swing programming java swing programming
java swing programming Ankit Desai
 
Presentation10 view navigation
Presentation10 view navigationPresentation10 view navigation
Presentation10 view navigationAnkit Desai
 
Presentation7 segment control
Presentation7 segment controlPresentation7 segment control
Presentation7 segment controlAnkit Desai
 
Presentation6 ui image_view
Presentation6 ui image_viewPresentation6 ui image_view
Presentation6 ui image_viewAnkit Desai
 
Presentation5 picker view
Presentation5 picker viewPresentation5 picker view
Presentation5 picker viewAnkit Desai
 
Presentation3 actionsheet alertview
Presentation3 actionsheet alertviewPresentation3 actionsheet alertview
Presentation3 actionsheet alertviewAnkit Desai
 
Presentation1 password
Presentation1 passwordPresentation1 password
Presentation1 passwordAnkit Desai
 
Presentation2 gesture control
Presentation2 gesture controlPresentation2 gesture control
Presentation2 gesture controlAnkit Desai
 

Mais de Ankit Desai (11)

java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transfer
 
Java RMI
Java RMIJava RMI
Java RMI
 
java swing programming
java swing programming java swing programming
java swing programming
 
JDBC
JDBCJDBC
JDBC
 
Presentation10 view navigation
Presentation10 view navigationPresentation10 view navigation
Presentation10 view navigation
 
Presentation7 segment control
Presentation7 segment controlPresentation7 segment control
Presentation7 segment control
 
Presentation6 ui image_view
Presentation6 ui image_viewPresentation6 ui image_view
Presentation6 ui image_view
 
Presentation5 picker view
Presentation5 picker viewPresentation5 picker view
Presentation5 picker view
 
Presentation3 actionsheet alertview
Presentation3 actionsheet alertviewPresentation3 actionsheet alertview
Presentation3 actionsheet alertview
 
Presentation1 password
Presentation1 passwordPresentation1 password
Presentation1 password
 
Presentation2 gesture control
Presentation2 gesture controlPresentation2 gesture control
Presentation2 gesture control
 

Último

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Último (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Java Beans

  • 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
  • 4. Advanced Java Classified e-Material 4/17 Agenda  JavaBeans Concepts  Writing a Simple Bean  Bean Properties  Manipulating Events  Bean Persistence  Introspection
  • 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
  • 15. Advanced Java Classified e-Material 15/17 Property Owner Property 1 Property 2 Property n PropertyChangeListner PropertyChange() Method Property 1 changed Property 2 changed Property n changed
  • 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
  • 39. Advanced Java Classified e-Material 39/17 Event Source Event Adapter Event Listener Register Event Listener Event Object Fire Event Provide interface Forward event Event Object
  • 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

Notas do Editor

  1. U. & P.U.Patel Department of Computer Engineering
  2. U. & P.U.Patel Department of Computer Engineering