be an in trod

Upload: avinash-bhat

Post on 10-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Be an in Trod

    1/27

    Java BeansJava Beans

  • 8/8/2019 Be an in Trod

    2/27

    What are Java Beans? ...What are Java Beans? ...

    Definition:Definition:

    A Java bean is a reusable software component .A Java bean is a reusable software component .They areThey areclasses written in theclasses written in the Java programming language

    SoftwareSoftware component is a software package thatcomponent is a software package thatencapsulates a set of related functionsencapsulates a set of related functions

  • 8/8/2019 Be an in Trod

    3/27

    Advantages of JavaBeansAdvantages of JavaBeans

    ItIt enablesenables developersdevelopers toto writewrite reusablereusablecomponentscomponents onceonce andand runrun themthem anywhereanywhere ----

    benefitingbenefiting fromfrom t h

    eth

    e platformplatform--independentindependent powerpowerofof JavaJava technologytechnology..

    ThisThis approachapproach notnot onlyonly savesave timetime ,money,money andandefforteffortbutbut produceproduce moremore reliablereliable applicationsapplications

    TheThe goal goal of of JavaBeansJavaBeans isis toto createcreate aa systemsystem

    wherebywhereby applicationapplication developersdevelopers cancan taketake aa set set of ofbeansbeans fromfrom aa stockstock librarylibrary andand wirewire themthem togethertogethertoto makemake aa fullfull applicationapplication

  • 8/8/2019 Be an in Trod

    4/27

    Features of JavaBeansFeatures of JavaBeans

    Support forSupport for introspectionintrospection Allowing user to analyze how a bean worksAllowing user to analyze how a bean works

    Support forSupport for customizationcustomization

    allowing a user to alter the appearance andallowing a user to alter the appearance and

    behavior of a beanbehavior of a bean

    Support forSupport for eventsevents

    Allowing beans to communicateAllowing beans to communicate

    Support forSupport for propertiesproperties

    Allowing the user to manipulate the beanAllowing the user to manipulate the beanprogrammatically and support customizationprogrammatically and support customization

    Support forSupport for persistencepersistence

    allowing a bean thathave been customized toallowing a bean thathave been customized to

    save their state and reloaded latersave their state and reloaded later

  • 8/8/2019 Be an in Trod

    5/27

    Designing java beanDesigning java bean

    PropertiesProperties

    EventsEvents IntrospectionIntrospection

    CustomizationCustomization

  • 8/8/2019 Be an in Trod

    6/27

    PropertiesProperties

    Allowing the user to manipulate the beanAllowing the user to manipulate the beanprogrammatically.programmatically.

    Several types ofproperties:Several types ofproperties:

    SimpleSimple

    IndexedIndexed

    BoundBound

    ConstrainedConstrainedA bean provide two methods for eachproperty :A bean provide two methods for eachproperty :

    one toone to getgetthe property and one tothe property and one to setsetthethepropertyproperty

  • 8/8/2019 Be an in Trod

    7/27

    Design Pattern rulesDesign Pattern rules

    For any property named P of type T the get and set methods has the

    following syntax

    1.Simple Properties publicT getP()public void setP ( T value)

    Here type can be integer or string

    2.Boolean Properties public boolean isP()public void setP(boolean value)

    Here type isboolean

    3.Indexed Properties public T[] getP()

    public void setP(T[] values)

    public T getP(int index)public void setP(int index,T value)

    Here type can be array of another type

  • 8/8/2019 Be an in Trod

    8/27

    Coding examples for PropertiesCoding examples for Properties

    packagepackage simpleBean.examplesimpleBean.example;;public classpublic class SimpleBeanSimpleBean

    {{

    private String name;private String name;

    private String password;private String password;public Stringpublic String getgetNameName()(){return name;}{return name;}

    public voidpublic void setsetNameName(String name(String name){ this.name =){ this.name =

    name;}name;}

    public Stringpublic String getPasswordgetPassword(){return password;}(){return password;}public voidpublic void setPasswordsetPassword (String name){(String name){

    this.passwordthis.password = password;}= password;}

    }}

  • 8/8/2019 Be an in Trod

    9/27

    Coding examples for PropertiesCoding examples for Propertiespackagepackage simpleBean.examplesimpleBean.example;;

    public classpublic class ArrayBeanArrayBean

    {{

    private String things[ ];private String things[ ];

    publicpublic String[ ]String[ ] getThingsgetThings()()

    {return things;}{return things;}

    public voidpublic void setThingssetThings (String things)(String things)

    {{ this.thingsthis.things = things;}= things;}

    publicpublic StringString getThingsgetThings ((intint ii)){return things[{return things[ii];}];}

    public voidpublic void setThingssetThings ((intint ii, String things), String things)

    { things[{ things[ii] = things;}] = things;}

  • 8/8/2019 Be an in Trod

    10/27

    EventsEvents

    A bean communicates with other beans by generatingA bean communicates with other beans by generating

    eventsevents

    Two types of objects are involved:Two types of objects are involved:

    Source objects.Source objects.

    Listener objects.Listener objects.

    SourceSourcefiresfires event, recipient (listener)event, recipient (listener) handleshandles the event.the event.

    Source must register listeners.Source must register listeners.Event

    source

    Event

    listenerFire event

    Event

    Object

    Register listener

  • 8/8/2019 Be an in Trod

    11/27

    Bean EventsBean Events

    Define a new Event class which extendsDefine a new Event class which extends

    java.util.EventObjectjava.util.EventObject class.egclass.eg TypeType EventEvent

    Define a new interface for listeners to implement, thisDefine a new interface for listeners to implement, this

    must be an extension ofmust be an extension ofjava.util.EventListenerjava.util.EventListener..egeg TypeTypeListenerListener

    The source bean provideThe source bean provide addadd method for registering tomethod for registering to

    allow event listeners to notify when an E event occurs.allow event listeners to notify when an E event occurs.

    public voidpublic void addaddTypeTypeListenerListener((TypeTypeListenerListener el)el)

    The source bean provideThe source bean provide removeremove method that allow amethod that allow a

    listener to unregister an interest to specific eventlistener to unregister an interest to specific event

    public voidpublic void removeremoveTypeTypeListenerListener((TypeTypeListenerListener el).el).

  • 8/8/2019 Be an in Trod

    12/27

    EventsEvents

    packagepackage eventBean.exampleeventBean.example;;

    public classpublic class PurchaseEventPurchaseEvent extendsextends Java.util.EventObjectJava.util.EventObject

    {{

    private Stringprivate String itemNameitemName;;

    publicpublic PurchaseEventPurchaseEvent(Object source, String(Object source, String itemNameitemName))

    {{

    super(source);super(source);

    this.itemNamethis.itemName==itemNameitemName;;

    }}public Stringpublic String getItemNamegetItemName(){return(){return itemNameitemName;};}

    }}

  • 8/8/2019 Be an in Trod

    13/27

    Events...Events...

    packagepackage eventBean.exampleeventBean.example;;

    public interfacepublic interface PurchaseListenerPurchaseListener extendsextends Java.util.EventListenerJava.util.EventListener

    {{

    public voidpublic void PurchaseMadePurchaseMade((PurchaseEventPurchaseEvent e){ }e){ }}}

  • 8/8/2019 Be an in Trod

    14/27

    Bound propertiesBound properties

    Aproperty that generates a notification whenAproperty that generates a notification whenthe property is modifiedthe property is modified is called ais called a boundboundpropertyproperty..

    It is aIt is a special eventspecial event

    A Bean fire aA Bean fire a PropertyChangeEventPropertyChangeEvent whenwhenone of its properties changes, in order to alertone of its properties changes, in order to alertother Beans (other Beans (PropertyChangeListenerPropertyChangeListener) to the) to the

    changechange

    TheThe getgetandand setsetmethods same as regularmethods same as regularpropertyproperty

  • 8/8/2019 Be an in Trod

    15/27

    TheThe addadd andand removeremove methods for the registrationmethods for the registrationandand unregistrationunregistration oflisteners that are notifiedoflisteners that are notifiedwhen any bound property value changewhen any bound property value change areare

    public voidpublic void

    addPropertyChangeListeneraddPropertyChangeListener((

    PropertyChangeListenerPropertyChangeListener el)el)

    public voidpublic void removePropertyChangeListenerremovePropertyChangeListener((PropertyChangeListenerPropertyChangeListener el)el)

  • 8/8/2019 Be an in Trod

    16/27

    Constrained propertyConstrained property When bean tries to set a property to an unacceptableWhen bean tries to set a property to an unacceptable

    value it generates or throws avalue it generates or throws a VetoEventVetoEvent such asuch aproperty is said to be constrained propertyproperty is said to be constrained property

    It is alsoIt is also special eventspecial event

    The source bean must send out aThe source bean must send out a

    PropertyChangeEventPropertyChangeEvent to the list of interestedto the list of interested

    VetoableChangeListenerVetoableChangeListener objects. If any of theseobjects. If any of these

    objects throws aobjects throws a PropertyVetoExceptionPropertyVetoException, the property, the property

    valuevalue is not changedis not changed, and propagated back to the, and propagated back to the

    propertyproperty setset methodmethod..

    public voidpublic void setsetPP((TT) throws) throws PropertyVetoExceptionPropertyVetoException el)el)

  • 8/8/2019 Be an in Trod

    17/27

    Methods for the registration andMethods for the registration and unregistrationunregistrationoflisteners that are notified when anyoflisteners that are notified when anyconstrained property value changesconstrained property value changes

    public voidpublic void addVetoableChangeListeneraddVetoableChangeListener((

    VetoableChangeListenerVetoableChangeListener el)el)

    public voidpublic void removeVetoableChangeListenerremoveVetoableChangeListener((

    VetoableChangeListenerVetoableChangeListener el)el)

  • 8/8/2019 Be an in Trod

    18/27

    IntrospectionIntrospection

    A mechanism that allowsA mechanism that allows analyzing a bean'sanalyzing a bean's designdesignpatterns to reveal the bean'spatterns to reveal the bean's properties, events, andproperties, events, andmethodsmethods..

    Two ways to analyze a bean:Two ways to analyze a bean:

    lowlow--level service .level service .

    enablingwide access to theenablingwide access to the structural internalsstructural internals of aof abean to provide advanced development features bybean to provide advanced development features byapplication builders.application builders.

    Highlevel service.Highlevel service.

    provide access toprovide access to limited portions of a bean'slimited portions of a bean'sinternals,tointernals,to develeporsdevelepors which typicallyconsist of awhich typicallyconsist of abean's publicproperties and methodsbean's publicproperties and methods

  • 8/8/2019 Be an in Trod

    19/27

    The JavaBeans supplies a set of classes andThe JavaBeans supplies a set of classes and

    interfaces to provide introspectioninterfaces to provide introspection

    IntrospectorIntrospector classclass

    determine the list ofproperties supported by a bean.determine the list ofproperties supported by a bean.

    BeanInfoBeanInfo interfaceinterface

    definesdefines aa set set of ofmethodsmethods t hatthat allowallow beanbean implementersimplementerstoto provideprovide additionaladditional informationinformation aboutabout theirtheir beanbean ..

    FeatureDescriptorFeatureDescriptor classclass

    provide a name and brief description of features in theprovide a name and brief description of features in thebean.bean.

  • 8/8/2019 Be an in Trod

    20/27

    .. BeanDescriptorBeanDescriptor

    This class provides global information about a bean.This class provides global information about a bean.

    EventSetDescriptorEventSetDescriptor This class represents a set of events that a bean isThis class represents a set of events that a bean is

    capable of generating.capable of generating.

    MethodDescriptoMethodDescriptorr

    Represents a publicly accessible method This classRepresents a publicly accessible method This classprovides methods for accessing information such as aprovides methods for accessing information such as amethod's parametersmethod's parameters..

    PropertyDescriptorPropertyDescriptor

    This class provides methods for accessing the type of aThis class provides methods for accessing the type of aproperty alongwith itsproperty alongwith its accessoraccessor methods and checkmethods and checkwhether it is bound or constrainedwhether it is bound or constrained

  • 8/8/2019 Be an in Trod

    21/27

    IndexedPropertyDescriptorIndexedPropertyDescriptor

    This class provides methods for accessing the type of anThis class provides methods for accessing the type of anindexed property alongwith itsindexed property alongwith its accessoraccessor method.method.

    ParameterDescriptorParameterDescriptor

    This class provide detailed parameter information forThis class provide detailed parameter information for

    bean developers .bean developers . FeatureDescriptorFeatureDescriptor

    This class serves as a common base class .ItThis class serves as a common base class .Itrepresents bean information that is common across allrepresents bean information that is common across allthese classes, such as the name of an event, method, orthese classes, such as the name of an event, method, orproperty.property.

  • 8/8/2019 Be an in Trod

    22/27

    CustomizationCustomization

    Customization allows a user to alter theCustomization allows a user to alter theappearance and behavior of a beanappearance and behavior of a bean

    It gives users the ability toIt gives users the ability to visuallyvisually modify amodify abeans properties to meet their needs.beans properties to meet their needs.

    useuse property sheetsproperty sheets to allowusers to maketo allowusers to makepropertychanges.propertychanges.

    Property sheet displays aProperty sheet displays a list ofpropertieslist ofpropertiesassociated with a bean.associated with a bean.

  • 8/8/2019 Be an in Trod

    23/27

    Eachpropertylisted should have aEachpropertylisted should have aproperty editorproperty editor associated with it.associated with it.

    Aproperty editor is a class that allows youAproperty editor is a class that allows youto edit the property of a bean visually.to edit the property of a bean visually.

    Allproperty editors must implement theAllproperty editors must implement thejava.beans.PropertyEditorjava.beans.PropertyEditor interfaceinterface..

    The easiestway to create a simpleThe easiestway to create a simplePropertyEditorPropertyEditor is to extend theis to extend the

    java.beans.PropertyEditorSupportjava.beans.PropertyEditorSupportclassclass

    It is aIt is a helper classhelper class that implementsthat implementsPropertyEditorPropertyEditor interface.interface.

  • 8/8/2019 Be an in Trod

    24/27

    Customization usingcustomizersCustomization usingcustomizers

    For more sophisticated beans, theFor more sophisticated beans, theJavaBeans has defined aJavaBeans has defined a CustomizerCustomizerinterface that behaves like ainterface that behaves like a wizardwizard

    allow

    ing th

    e user toallow

    ing th

    e user to configureconfigure th

    at bean inth

    at bean inusefulway.usefulway.

    Wizards areWizards are graphicaluser interfacesgraphicaluser interfaces thatthatguide the user step by step through theguide the user step by step through the

    customization process ofusers configuringcustomization process ofusers configuringbeans.beans.

  • 8/8/2019 Be an in Trod

    25/27

    Customizers often attempt to provideCustomizers often attempt to provide

    editing facilities within the contextediting facilities within the contextof aof aseries of questionsseries of questions

    All bean customizers must implement theAll bean customizers must implement thejava.beans.Customizerjava.beans.Customizer interfaceinterface andandextend theextend thejava.awt.Paneljava.awt.Panel classclass..

  • 8/8/2019 Be an in Trod

    26/27

    PersistencePersistence

    Persistence is the mechanism bywhichPersistence is the mechanism bywhichbeans are stored in a place for later use.beans are stored in a place for later use.

    Persistence in JavaBeans is tightlylinkedPersistence in JavaBeans is tightlylinked

    toto serializationserialization in java.in java. Serialization is the process of reading orSerialization is the process of reading orwriting an object to a file.writing an object to a file.

    JavaBeans uses serialization is in itsJavaBeans uses serialization is in itsautomatic approach to persistence, whichautomatic approach to persistence, whichinvolvesinvolves storing and retrieving a beanstoring and retrieving a beanbased on itsbased on its propertiesproperties ..

  • 8/8/2019 Be an in Trod

    27/27