0% found this document useful (0 votes)
10 views10 pages

Unit 3

JavaBeans are classes that encapsulate multiple objects into a single object, promoting modularity and reusability in applications. They must have a public no-arg constructor, implement Serializable, and have private properties with public getters and setters. JavaBeans support introspection, persistence, and event handling, but have limitations including mutability and boilerplate code for property management.

Uploaded by

bikram.sah.2023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

Unit 3

JavaBeans are classes that encapsulate multiple objects into a single object, promoting modularity and reusability in applications. They must have a public no-arg constructor, implement Serializable, and have private properties with public getters and setters. JavaBeans support introspection, persistence, and event handling, but have limitations including mutability and boilerplate code for property management.

Uploaded by

bikram.sah.2023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

JavaBeans

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;

public class Person implements Serializable {


private String name;
private int age;

// Public no-arg constructor


public Person() {
}

// Getter method for name


public String getName() {
return name;
}

// Setter method for name


public void setName(String name) {
this.name = name;
}

// Getter method for age


public int getAge() {
return age;
}

// Setter method for age


public void setAge(int age) {
this.age = age;
}
}

Advantages of a JavaBean are:


1. Reusability: JavaBeans are designed to be reusable components that can be easily integrated into various
applications. This modularity reduces redundancy and promotes code reuse.
2. Exposure to other applications: One of the most important advantages of a JavaBean is, the events properties
and the methods of a bean can be exposed directly to another application.
3. Supports events: A JavaBean can be registered to receive events from other objects. However, we can also
generate events that can be sent to other objects.
4. Ease of configuration: We can easily use auxiliary software to configure the JavaBean. However, we can also
save the configuration setting of a JavaBean to persistent storage.
5. Portable: As JavaBeans are built in Java, we can easily port them to any other platform that contains JRE.
6. Lightweight: JavaBeans are light weighted, I.e., we don't need to fulfill any special requirement to use it. Also, it
is very easy to create them. However, it doesn't need a complex system to register components with JRE.
Disadvantages of a JavaBean are:
1. Mutable objects: JavaBeans are mutable. So, it can't take advantages of immutable objects.
2. Boilerplate: Creating the setter and getter method for each property separately may lead to the boilerplate
code.
3. Limited to Java Environment: JavaBeans are inherently tied to the Java programming language and ecosystem.
This limits their use in heterogeneous environments where components may need to interact with non-Java
systems or languages.

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;

// Getter for name property


public String getName() {
return name;
}

// Setter for name property


public void setName(String name) {
this.name = 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);
}

// Setter for items property


public void setItem(int index, String item) {
items.set(index, item);
}

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);
}

public void addTemperatureChangeListener(TemperatureChangeListener listener) {


l.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;
}

For Boolean properties:


Design pattern: Public boolean isName()
Example:
private boolean on;
public boolean isOn() {
return on;
}

2. Mutator Methods: Used to set the value of a property.


Design pattern: public void setName(arg)
Example:
Private int age;
Public void setAge(int age){
this.age = age;
}

3. Action Methods: Perform specific actions or operations.


Design pattern: doSomething()
Example:
private double balance;
// Method to deposit an amount
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}

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;

class Person implements Serializable {


private String name;
private int age;

public String getName() {


return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}

class PersonBeanInfo implements BeanInfo {

@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;
}
}
}

public class Main{


public static void main(String args[]) throws IntrospectionException{
BeanInfo info = Introspector.getBeanInfo(Person.class); //Will use the PresonBeanInfo

BeanDescriptor beanDescriptor = info.getBeanDescriptor();


System.out.println("Class name: " + beanDescriptor.getName());

PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();

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;

class Person implements Serializable {


private String name;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public Person() {}

public Person(String name) {


this.name = name;
}

public String getName() {


return name;
}

public void setName(String name) {


String oldName = this.name;
this.name = name;
pcs.firePropertyChange("name", oldName, name);
}

public void addPropertyChangeListener(PropertyChangeListener listener) {


pcs.addPropertyChangeListener(listener);
}
}

public class Main{


public static void main(String args[]){
Person person = new Person("Raj Poudel");
person.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
System.out.println("Property " + e.getPropertyName() + " changed from " +
e.getOldValue() + " to " + e.getNewValue());
}
});

// 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;

class Person implements Serializable {


private String name;
private int age;
private VetoableChangeSupport vcs = new VetoableChangeSupport(this);

public Person() {}

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return name;
}

public void setName(String name){


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) throws PropertyVetoException {


int oldAge = this.age;
PropertyChangeEvent event = new PropertyChangeEvent(this, "age", oldAge, age);
vcs.fireVetoableChange(event);
this.age = age;
}

public void addVetoableChangeListener(VetoableChangeListener listener) {


vcs.addVetoableChangeListener(listener);
}
}

public class Main{


public static void main(String args[]){
Person person = new Person("Amit", 25);
person.addVetoableChangeListener(new VetoableChangeListener() {
@Override
public void vetoableChange(PropertyChangeEvent e) throws PropertyVetoException {
if ("age".equals(e.getPropertyName())) {
int newAge = (int) e.getNewValue();
if (newAge < 0) {
throw new PropertyVetoException("Age cannot be negative", e);
}
}
System.out.println(e.getPropertyName() + " cahanged from " +
e.getOldValue() + " to " + e.getNewValue());
}
});

// Attempt to change properties


try {
person.setName("Aman");
person.setAge(30);
person.setAge(15); // This will throw a PropertyVetoException
} catch (PropertyVetoException e) {
System.out.println(e.getMessage());
}
}
}

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.*;

class Person implements Serializable {


private String name;
private int age;

public Person() {}

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return name;
}

public void setName(String name){


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age){


this.age = age;
}
}
public class JavaBeans {

public static void main(String[] args) throws Exception {


Person person = new Person("Amit Poudel", 25);

FileOutputStream fileOut = new FileOutputStream("person.ser");


ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
System.out.println("Serialized data is saved in person.ser");

FileInputStream fileIn = new FileInputStream("person.ser");


ObjectInputStream in = new ObjectInputStream(fileIn);
person = (Person) in.readObject();
System.out.println("Deserialized Person...");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}

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.

3. BeanDescriptor: Describes a bean, including its customizer class.


 Class<?> getBeanClass(): Gets the bean's class.
 void setCustomizerClass(Class<?> customizerClass): Sets the customizer class for the bean.
 Class<?> getCustomizerClass(): Gets the customizer class for the bean.

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.

5. EventSetDescriptor: Describes a set of events that a bean can fire.


 String getName(): Gets the name of the event set.
 Class<?> getListenerType(): Gets the listener type.
 getListenerMethods(): Gets the listener methods.
 getAddListenerMethod(): Gets the method for adding a listener.
 getRemoveListenerMethod(): Gets the method for removing a listener.

6. MethodDescriptor: Describes a method of a bean.


 MethodDescriptor(Method method): Constructor for a method descriptor.
 getMethod(): Gets the method described by this descriptor.

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.

You might also like