Unit 3
Unit 3
Introduction: Java Beans are classes that encapsulate many objects into a single object (the bean). It helps in accessing
these object from multiple places. It is particularly useful for building complex applications from simple, modular
components.
Characteristics of JavaBean:
1. Public no-arg constructor: A Java Bean must have a public no-argument constructor to allow easy instantiation.
2. Serializable: Java Beans should implement the Serializable interface.
3. Properties: All properties in java bean must be private with public getters and setter methods.
Example:
import java.io.Serializable;
Introspection: Introspection in JavaBeans is a process that allows a framework or tool to analyze a JavaBean's
properties, events, and methods dynamically at runtime. This capability is crucial for development tools that provide
visual component manipulation, such as Integrated Development Environments (IDEs), which can automatically detect
and configure JavaBeans without explicit coding.
Key Concepts:
Properties: Attributes of the bean that can be read or modified. They are typically exposed via getter and setter
methods.
Events: Mechanisms for the bean to communicate with other components. Beans can fire events and register
listeners for these events.
Methods: Functions that the bean exposes for external interaction.
Properties Design Pattern: Properties in Java Beans are usually implemented using a combination of private instance
variables and public getters/setters methods. However, there are several design patterns that can be used to implement
properties in Java Beans in a more efficient and maintainable manner. Here are a few design patterns for properties in
Java Beans:
1. Simple Property Pattern: This pattern involves creating a private instance variable for each property and
providing a public getter and setter method for each variable. This pattern is simple and straightforward, but can
become tedious if there are a large number of properties to manage.
This can be done by the following design pattern:
public returnType get()
public void set(dataType arg)
Example:
private String name;
2. Indexed Property Pattern: This pattern is used when you need to manage a collection of related properties. For
example, if you have a Java Bean that represents a database record, you might want to provide access to the
individual fields in the record using an index. In this pattern, you create a private array to hold the property
values and provide getter and setter methods that take an index parameter.
This can be done by the following design pattern:
public returnType get(int index);
public void set(int index, returnType value);
Example:
private List<String> items = new ArrayList<>();
// Getter for items property
public String getItem(int index) {
return items.get(index);
}
Event Design Pattern: Beans can generate events and send them to other objects. This pattern is essential for
building interactive and responsive applications where different parts of the system need to react to changes or actions
triggered by user interactions, system events, or other sources.
This can be done by the following design pattern:
public void addListener(Listener eventListener)
Example:
public void onClickListener(ActionListener listener) {
button.add(listener);
}
Method Design Pattern: Methods in JavaBeans follow specific naming conventions to ensure consistency and
compatibility with tools, frameworks, and libraries that support JavaBeans. Common naming conventions include:
1. Accessor Methods: Used to retrieve the value of a property.
For non- Boolean properties:
Design pattern: public returnType getName()
Example:
Private Int age;
public int getAge(){
return age;
}
BeanInfo Interface: The BeanInfo interface enables to explicitly control what information is available. The BeanInfo
interface is a part of the java.beans package and it allows you to provide additional metadata about a JavaBean. This
metadata includes information such as the name of the bean, its properties, and its events.
Here are some of the methods provided by the BeanInfo interface:
1. beanDescriptor(): This method returns a BeanDescriptor object that provides a description of the bean.
2. getPropertyDescriptors(): This method returns an array of PropertyDescriptor objects that describe the
properties of the bean.
3. getEventSetDescriptors(): This method returns an array of EventSetDescriptor objects that describe the events
fired by the bean.
Example:
import java.awt.Image;
import java.beans.*;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
@Override
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(Person.class);
}
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
PropertyDescriptor name, age;
try {
name = new PropertyDescriptor("uname", Person.class);
age = new PropertyDescriptor("uaddress", Person.class);
return new PropertyDescriptor[] { name,age};
} catch (IntrospectionException ex) {
Logger.getLogger(PersonBeanInfo.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
System.out.println("Properties:");
for (PropertyDescriptor pd : propertyDescriptors) { //for-each loop
System.out.println("Name: " + pd.getName()); //Return the name of the property
System.out.println(" Type: " + pd.getPropertyType()); //Returns the type of the property (e.g. String)
System.out.println(" Read Method: " + pd.getReadMethod()); //Returns the getter method
System.out.println(" Write Method: " + pd.getWriteMethod()); //Return the setter method
System.out.println();
}
}
}
Output:
Class name: Person
Properties:
Name: age
Type: int
Read Method: public int storeprocedure.Person.getAge()
Write Method: public void storeprocedure.Person.setAge(int)
Name: class
Type: class java.lang.Class
Read Method: public final native java.lang.Class java.lang.Object.getClass()
Write Method: null
Name: name
Type: class java.lang.String
Read Method: public java.lang.String storeprocedure.Person.getName()
Write Method: public void storeprocedure.Person.setName(java.lang.String)
Bound Property: A Bean that has a bound property generates an event when the property is changed. It is the
property of a JavaBean that inform its listeners about changes in its values. It is implemented using the
PropertyChangeSupport class and its methods.
Bound Property is always registered with PropertyChangeListener. The event is of type PropertyChangeEvent
and is sent to objects that previously registered an interest in receiving such notifications.
addPropertyChangeListener method is created to add listener.
Example:
import java.beans.*;
import java.io.Serializable;
// Change properties
person.setName("Raju Poudel");
}
}
Output:
name changed from Raj Poudel to Raju Poudel
Constrained Property: Constrained properties in JavaBeans involve using the PropertyChangeEvent class along with
the VetoableChangeSupport class to notify listeners about property changes and allow them to veto these changes if
necessary.
Those other objects have the ability to veto(reject) the proposed change. This allows a bean to operate
differently according to the runtime environment. So, it is protected from being changed by other JavaBeans.
Example:
import java.beans.*;
import java.io.Serializable;
public Person() {}
Output:
Age changed from 25 to 30
Age cannot be less than 18
Persistence: JavaBeans persistence refers to the ability of JavaBeans to be serialized and deserialized, allowing their
state to be saved to a storage medium (like a file or database) and restored later. This capability is essential for many
applications, such as saving user settings, caching data, or transferring objects between different parts of an application
or between applications.
Serialization is the process of converting an object's state to a byte stream, which can then be written to a file,
sent over a network, or stored in a database. In Java, this is achieved by implementing the Serializable interface.
Deserialization is the reverse process of converting a byte stream back into a copy of the original object.
Example:
import java.io.*;
public Person() {}
Output:
Serialized data is saved in person.ser
Deserialized Person...
Name: Amit Poudel
Age: 25
Note: At first, instance of Person created and writes it to a file named person.ser. The ObjectOutputStream class is used
to write the Person object to the file. Then read the Person object from the person.ser file and prints its properties.The
ObjectInputStream class is used to read the Person object from the file.
Customizers: A Bean developer can provide a customizer that helps another developer configure the Bean. A
customizer can provide a step-by-step guide through the process that must be followed to use the component in a
specific context. Online documentation can also be provided. A Bean developer has great flexibility to develop a
customizer that can differentiate his or her product in the marketplace.
All customizers must:
Extend java.awt.Component or one of its subclasses.
Implement the java.beans.Customizer interface. This means implementing methods to register
PropertyChangeListener objects, and firing property change events at those listeners when a change to the
target Bean has occurred.
Implement a default constructor.
Associate the customizer with its target class via BeanInfo.getBeanDescriptor.
Java Beans API: The Java Beans functionality is provided by a set of classes and interfaces in the java.beans package.
Beans are reusable software programs that you can develop and assemble easily to create sophisticated applications.
JavaBeans technology is based on the JavaBeans specification. The JavaBeans API and its implementation are contained
in the java.beans package.
Here is a detailed overview of the key classes and interfaces:
1. Introspector: Provides methods for analyzing a bean to determine its properties, events, and methods.
BeanInfo getBeanInfo(Class<?> beanClass): Gets the BeanInfo for a bean class.
2. BeanInfo: Allows explicit control over the introspection process. By implementing BeanInfo, you can provide
additional information about the bean.
BeanDescriptor getBeanDescriptor(): Gets the BeanDescriptor for the bean.
PropertyDescriptor[] getPropertyDescriptors(): Gets the PropertyDescriptor objects for the bean's properties.
EventSetDescriptor[] getEventSetDescriptors(): Gets the EventSetDescriptor objects for the bean's event sets.
MethodDescriptor[] getMethodDescriptors(): Gets the MethodDescriptor objects for the bean's methods.
4. PropertyDescriptor: Describes a property of a bean, including its getter and setter methods.
getReadMethod(): Gets the getter method for the property.
getWriteMethod(): Gets the setter method for the property.
void setReadMethod(Method readMethod): Sets the getter method for the property.
void setWriteMethod(Method writeMethod): Sets the setter method for the property.
7. PropertyChangeListener and PropertyChangeSupport: Used to support property change events, which notify
listeners about changes to a bean's properties.
addPropertyChangeListener(PropertyChangeListener listener): Adds a property change listener.
removePropertyChangeListener(PropertyChangeListener listener): Removes a property change listener.
firePropertyChange(String propertyName, Object oldValue, Object newValue): Fires a property change event.
8. VetoableChangeListener and VetoableChangeSupport: Used to support vetoable change events, which allow
listeners to veto property changes.
addVetoableChangeListener(VetoableChangeListener listener): Adds a vetoable change listener.
removeVetoableChangeListener(VetoableChangeListener listener): Removes a vetoable change listener.
fireVetoableChange(String propertyName, Object oldValue, Object newValue) throws PropertyVetoException: Fires a
vetoable change event.
9. Customizer: Interface that should be implemented by any GUI component that customizes the properties of a
bean.
setObject(Object bean): Sets the object to be customized.