Java Programming/Java Beans
From Wikibooks, the open-content textbooks collection
[edit] What is a Java Bean?
A Java Bean is a Java class that follows the Sun Java Beans Standard. (The term Java Bean or simply bean also refers to the instances of a Java Bean class.) The Java Beans standard provides a framework for creating objects to be used by GUI tools, including Java development environments. But in more common usage, a bean is a serializable class that follows the Java Beans naming conventions for its properties. These naming standards make it easy to use Java Introspection
To follow these standards, the bean needs one or more properties abstractions which represent different state values of an object. A property has a name (a valid Java identifier) and a type (either a reference type, a primitive type or an array type). By default, the properties of a Java Bean class are inferred by the presense of either a getter method, a setter method, or both:
- A getter method which is used to obtain the value of the property from a bean. The name is usually of the form
getPropertyName. For example, the getter method for the String propertywhiskeyispublic String getWhiskey(). For boolean properties (those whose type is boolean, the convention is to use the naming patternisPropertyName.
isDiscounted() would be the getter method for a boolean property named discounted. Thus, the method signature of most getters is public PropertyType getPropertyName() or public boolean isPropertyName()
- A setter method which is used to assign a value to a bean's property. A setter method is a method of the form
public void setPropertyName(PropertyType value). For the previous example, the setter could be invoked assetWhiskey("bourbon");.
As per the Java Beans standard, getters and setters defined as described above automatically determine the properties of the class. However, by creating java.beans.PropertyDescriptor classes, you can specify alternate implemenations by explicitly declaring the property names and the getter and/or setter methods for each property.
Properties are often implemented with private instance variables, but this is not required.
[edit] A Simple Java Bean
This is an example of a simple Java Bean type named Puppy with the properties int age and String color.
class Puppy implements java.io.Serializable
{
private static final long serialVersionUID = 2006L;
private String color;
private int age;
public String getColor()
{
return color;
}
public void setColor(String color)
{
this.color = color;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
[edit] Uses
In Java and J2EE programming, the structured definition of bean properties is very useful for comparing a single common property across several objects that are not and should not be related by inheritance.
For example, a program may contain both a bean representing a company's employees, and another containing a list of buildings that a company occupies. A programmer writing a function called listAssetNames() wants to write a simple way of getting the field "name" from several beans that can get the field from both Employee and Building beans, and that can be easily adapted to get the same field from other types of beans that may not be written yet.
While this could be done by rewriting both Employee and Building so that they each inherit from one class named NamedObject, or by creating a NamedObject interface, both methods have their own problems. Using inheritence is limiting, as each child class can only inherit from one parent class, which limits the number of different classes that can share properties, as well as the number of common properties that can be shared. Furthermore, using inheritace to express relationships other than a simple "is-a" relationship can be confusing, as can looking through dozens of class definitions to find where a single "dumb" getter function is implemented. Creating an interface fixes the problems caused by the multiple inheritance rule, as a class can use any number of interfaces, but it still requires every shared property to be explicitly spelled out.
The simplest,most elegant way to deal with this type of relationship is by reading the bean properties using introspection. The jakarta BeanUtils package is a common way of handling objects that need to be related in this way, as it takes advantage of the regularity of JavaBean naming conventions.
[edit] Get property from a java bean
importorg.apache.commons.beanutils.PropertyUtils;try{ObjectmyValue = PropertyUtils.getSimpleProperty(o, propertyName); }catch(IllegalAccessException e) { // --- Handle exception -- }catch(InvocationTargetException e) { // --- Handle exception -- }catch(NoSuchMethodException e) { // --- Handle exception -- }
or
publicstaticObjectgetProperty(Objecto,StringpropertyName) {if(o ==null|| propertyName ==null|| propertyName.length() < 1) {returnnull; } // --- Based on the property name build the getter method name ---StringmethodName = "get" + propertyName.substring(0,1).toUpperCase() + propertyName.substring(1);Objectproperty =null;try{ java.lang.Class c = o.getClass(); java.lang.reflect.Method m = c.getMethod(methodName,null); property = m.invoke(o,null); }catch(NoSuchMethodException e) { // --- Handle exception -- }catch(SecurityException e) { // --- No permission; Handle exception -- }returnproperty; }

