0% found this document useful (0 votes)
0 views

java-beans

cours en java-bean
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

java-beans

cours en java-bean
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

Unit-6: Java Beans:


6.1 What is a Java Bean?

 A Java Bean is a software component that has been designed to be reusable in variety of
different environments.
 There is no restriction on the capability of a Bean. It may perform a simple function,
such as spelling check of a document, or a complex function such as forecasting the
performance of a stock portfolio.
 A Bean may be visible to an end user (ex. A button)
 A Bean may be invisible to a user (ex. Software to decode a stream of multimedia
information in a real time)
 A Bean may be designed to work autonomously on a user’s workstation or to work in
cooperation with a set of other distributed components.

 JavaBeans makes it easy to reuse software components.


 Developers can use software components written by others without having to
understand their inner workings.
 To understand why software components are useful, think of a worker assembling a car.
Instead of building a radio from scratch, for example, she simply obtains a radio and
hooks it up with the rest of the car.

Rules to make a class as Java Bean


 Must have a zero-argument (empty) constructor,
 you can satisfy this requirement either by explicitly defining such a constructor or by
omitting all constructors
 Should have no public instance variables (fields)
 Persistent values should be accessed through methods called getters and setters

 Usual rule to turn method name into property name


– Drop the word “get” or “set” and change the next letter to lowercase.
 Again, instance variable name is irrelevant.
• Method name: getUserFirstName()
• Property name: userFirstName

• Exception 1: boolean properties


– If getter returns boolean or Boolean

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 1


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

• Method name: isPrime() not setPrime() (but it is not compulsary)


• Property name: prime

• Exception 2: consecutive uppercase letters


– If two uppercase letters in a row after “get” or “set”
• Method name: getURL()
• Property name: URL (not uRL)

• In addition to these rules its common though it is not compulsory to implement


Serializable interface.
• What is the use of using Serializable interface?
– The Serializable interaface indicates that a class contains get and set methods that
another class can use to read or write an object’s instance variables.
– If a bean class implements Serializable interface then, some servlet engines can
save and restore this objects if that’s nessessary.
– Ex: tomcat container can save the User object’s state before it shuts down. And
can restore when it starts up next time

6.2 Advantages of Java Beans

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


 The properties, events, and methods of a Bean that are exposed to an application
builder tool can be controlled.
 A Bean may be designed to operate correctly in different locales, which makes it useful
in global markets.
 Auxiliary software can be provided to help a person configure a Bean. This software is
only needed when the design-time parameters for that component are being set.
 The configuration settings of a Bean can be saved in persistent storage and restored at a
later time.

A Bean may register to receive events from other objects and can generate events that are sent to
other objects

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 2


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

6.3 A Simple Java Bean Program?

File: BeanDemo.Java

import java.io.Serializable;
public class BeanDemo implements Serializable
{
private String sname;
private String usn;
Getter Method
public void setsname(String sname)
{
For every Private Data
this.sname=sname; member of a bean class in
} order to access it, it is
public void setusn(String usn) compulsory to keep a getter
{ and setter method
this.usn=usn; Setter Method
}
public String getsname()
{
return sname;
}
public String getusn()
{
return usn;
}
}

File: BeanJSP-1.JSP

<html>
<body>
<jsp:useBean id="stu" scope="request“ class="beans.BeanDemo"/>
<jsp:setProperty name="stu" property="*"/>
<jsp:forward page="prog9b.jsp" />
</body>
</html>

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 3


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

File: BeanJSP-2.JSP

<html>
<body>
<jsp:useBean id="stu" scope="request" class="beans.Prog9" />
Name: <jsp:getProperty name="stu" property="sname"/></br>
USN: <jsp:getProperty name="stu" property="usn"/></br>
Branch: <%out.print(stu.getBranch());%></br>
</body>
</html>

File Name: BeanDemo.html

<html>
<body><center><br><br>
<form action="BeanJsp-1.jsp" method="post">
Enter Name: <input type="text" name="sname"><br>
Enter usnno.: <input type="text" name="usn"><br>
Enter Branch: <input type="text" name="branch"><br><br>
<input type="submit" value="submit">
</center>
</form></body></html</html>

Explanation of the Above Program:

The program contains four files:

1) FormData.html  this file is just used to pass the data to JSP File

2) BeanDemo  Original Bean File which takes the form data as Private variables and
contains getter and setter methods for it.

3) BeanJsp-1.jsp  this file takes the data from HTML file and stores the contents in Bena
File, this part of storing data is done by using the line

<jsp:setProperty name="stu" property="*"/>

Here * means all properties like, if bean file


contains name and age it will set value for the
property name and age.

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 4


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

4) BeanJsp-2.jsp  this file is called from BeanJsp-1.jsp by JSP action tag forward, this file
is used to display the contents stored in BeanDemo.java class

Name: <jsp:getProperty name="stu" property="sname"/></br>


USN: <jsp:getProperty name="stu" property="usn"/></br>

6.4 The Java Beans API

 The Java Beans functionality is provided by a set of classes and interfaces in the
java.beans package.

Class Introspector

 The Introspector class provides a standard way for tools to learn about the properties,
events, and methods supported by a target Java Bean.
 For each of those three kinds of information, the Introspector will separately analyze the
bean's class and superclasses looking for information and use that information to build a
BeanInfo object that describes the target bean.
 For each class "Foo", explicit information may be available if there exists a corresponding
"FooBeanInfo" class that provides a non-null value when queried for the information.
 If a class provides explicit BeanInfo about itself then we add that to the BeanInfo
information we obtained from analyzing any derived classes.
 We then proceed to analyze the class's superclass and add in the information from it.

What is 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
 decapitalize(String name) : Utility method to take a string and convert it to normal
Java variable name.
 flushCaches() : Flush all of the Introspector's internal caches.
 flushFromCaches(Class classname) : Flush the Introspector's internal cached
information for a given class.
 getBeanInfo(Class beanClass) : Introspect on a Java Bean and learn about all its
properties, exposed methods, and events.

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 5


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

 getBeanInfo(Class beanClass, Class stopClass) : Introspect on a Java bean and learn all
about its properties, exposed methods, below a given "stop" point.
 getBeanInfo(Class beanClass, int flags) : Introspect on a Java bean and learn about all
its properties, exposed methods, and events, subject to some control flags.
 getBeanInfoSearchPath() : Gets the list of package names that will be used for finding
BeanInfo classes.
 setBeanInfoSearchPath(String[] path) : Change the list of package names that will be
used for finding BeanInfo classes.

Introspection Sample

The following example represents code to perform introspection:

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;

public String getName()


{
return this.name;
}

public int getSize()


{
return this.size;
}

public void setSize( int size )


{
this.size = size;
}
public static void main( String[] args ) throws IntrospectionException
{
BeanInfo info = Introspector.getBeanInfo( SimpleBean.class );
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
System.out.println( pd.getName() );
} }

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 6


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

 This example creates a non-visual bean and displays the following properties derived
from the BeanInfo object:
o class
o name
o size

 Note that a class property was not defined in the SimpleBean class.
 This property was inherited from the Object class. To get properties defined only in the
SimpleBean class, use the following form of the getBeanInfo method:
Introspector.getBeanInfo( SimpleBean.class, Object.class );

6.5 Class PropertyDescriptor  java.beans.PropertyDescriptor

java.lang.Object

java.beans.FeatureDescriptor

java.beans.PropertyDescriptor

 A PropertyDescriptor object is a type of FeatureDescriptor that describes a single property


of a Java bean.
 The BeanInfo class for a Java bean optionally creates and initializes
PropertyDescriptor objects to describe the properties that the bean supports.
 Typically, only application builders and similar tools use the “get” and “is” methods to
obtain this property description information.
 You create a PropertyDescriptor by specifying the name of the property and
the Class object for the bean.
 If you have not followed the standard "design patterns" for accessor method naming,
you may also specify the accessor methods for the property.
 Once a PropertyDescriptor is created, the setBound() and setConstrained() methods allow
you to specify whether the property is bound and/or constrained.
 setPropertyEditorClass() allows you to specify a specific property editor that should be
used to edit the value of this property (this is useful, for example, when the property is
an enumerated type with a specific list of supported values).
 The methods of the FeatureDescriptor superclass allow additional information about the
property to be specified.

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 7


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

public class PropertyDescriptor extends FeatureDescriptor


o A PropertyDescriptor describes one property that a Java Bean exports via a pair
of accessor methods.

 PropertyDescriptor(String, Class)
o Constructs a PropertyDescriptor for a property that follows the standard Java
convention by having getFoo and setFoo accessor methods.
 PropertyDescriptor(String, Class, String, String)
o This constructor takes the name of a simple property, and method names for
reading and writing the property.
 PropertyDescriptor(String, Method, Method)
o This constructor takes the name of a simple property, and Method objects for
reading and writing the property.

 createPropertyEditor(Object bean)
o Constructs an instance of a property editor using the current property editor
class.
 equals(Object obj)
o Compares this PropertyDescriptor against the specified object.
 getPropertyEditorClass()
o Gets any explicit PropertyEditor Class that has been registered for this property.
 getPropertyType()  Gets the Class object for the property.
 getReadMethod()  Gets the method that should be used to read the property value.
 getWriteMethod() Gets the method that should be used to write the property value.
 hashCode()  Returns a hash code value for the object.
 isBound()  Updates to "bound" properties will cause a "PropertyChange" event to get
fired when the property is changed.
 isConstrained()  Attempted updates to "Constrained" properties will cause a event to
get fired when the property is changed.
 setBound(boolean bound)
o Updates to "bound" properties will cause a "PropertyChange" event to get fired
when the property is changed.
 setConstrained(boolean constrained)
o Returns the class for the desired PropertyEditor. Normally, property editors will
be found using the property editor manager.
 setPropertyEditorClass(Class propertyEditorClass)
o Normally PropertyEditors will be found using the PropertyEditorManager.
 setReadMethod(Method readMethod)

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 8


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

o Sets the method that should be used to read the property value.
 setWriteMethod(Method writeMethod)
o Sets the method that should be used to write the property value.

6.6 Class EventSetDescriptor  java.beans.EventSetDescriptor

java.lang.Object
java.beans.FeatureDescriptor
java.beans.EventSetDescriptor

public class EventSetDescriptor extends FeatureDescriptor

 An EventSetDescriptor describes a group of events that a given Java bean fires.


 The given groups of events are all delivered as method calls on a single event listener
interface, and an event listener object can be registered via a call on a registration
method supplied by the event source.

Constructor Details:

public EventSetDescriptor(Class<?> sourceClass,


String eventSetName,
Class<?> listenerType,
String listenerMethodName)
throws IntrospectionException

 Creates an EventSetDescriptor assuming that you are following the most simple
standard design pattern where a named event "fred" is (1) delivered as a call on the
single method of interface FredListener, (2) has a single argument of type FredEvent, and
(3) where the FredListener may be registered with a call on an addFredListener method
of the source component and removed with a call on a removeFredListener method.

Parameters:
sourceClass - The class firing the event.
eventSetName - The programmatic name of the event. E.g. "fred". Note that this should
normally start with a lower-case character.
listenerType - The target interface that events will get delivered to.
listenerMethodName - The method that will get called when the event gets delivered to its
target listener interface.

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 9


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

Throws:
IntrospectionException - if an exception occurs during introspection.

Method Detail

getListenerType

public Class<?> getListenerType()


Gets the Class object for the target interface.
Returns:
The Class object for the target interface that will get invoked when the event is fired.

getListenerMethods

public Method[] getListenerMethods()


Gets the methods of the target listener interface.
Returns:
An array of Method objects for the target methods within the target listener interface that
will get called when events are fired.

getListenerMethodDescriptors:

public MethodDescriptor[] getListenerMethodDescriptors()


Gets the MethodDescriptors of the target listener interface.
Returns:
An array of MethodDescriptor objects for the target methods within the target listener
interface that will get called when events are fired.

getAddListenerMethod

public Method getAddListenerMethod()


Gets the method used to add event listeners.
Returns: The method used to register a listener at the event source.

getRemoveListenerMethod

public Method getRemoveListenerMethod()


Gets the method used to remove event listeners.
Returns: The method used to remove a listener at the event source.

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 10


Department of MCA TEA-I-Unit-6 – Java Beans-Notes KNS Institute of Technology

6.7 Class MethodDescriptor

java.lang.Object
java.beans.FeatureDescriptor
java.beans.MethodDescriptor

public class MethodDescriptor extends FeatureDescriptor

 A MethodDescriptor describes a particular method that a Java Bean supports for


external access from other components.

Constructor Summary
MethodDescriptor(Method method)
Constructs a MethodDescriptor from a Method.
MethodDescriptor(Method method, ParameterDescriptor[] parameterDescriptors)
Constructs a MethodDescriptor from a Method providing descriptive information for each of
the method's parameters.

Method Summary
Method getMethod()
Gets the method that this MethodDescriptor encapsualtes.
ParameterDescriptor[] getParameterDescriptors()
Gets the ParameterDescriptor for each of this MethodDescriptor's
method's parameters.

Lecturer: Syed Khutubuddin Ahmed Contact: [email protected] Page 11

You might also like