JSP Tag Libraries

Скачать в pdf «JSP Tag Libraries»

This design should accomplish all our defined goals. Our abstract design will become much more comprehensible as we look at our implementation and an example.

10.5.3 FieidGetter and ReflectionFieldGetter

Let’s start by looking at the FieidGetter interface, which provides one method to set the object whose fields we’ll want to retrieve and a second method to get those fields from the object. We present this interface in listing 10.15, along with an implementation of it called RefiectionFieidGetter whose job is to implement a FieidGetter that gets JavaBeans properties (through reflection).

Listing 10.15 Source code of FieidGetter and ReflectionFieldGetter

package book.utii;

import java.beans.IntrospectionException;

import java.lang.reflect.InvocationTargetException;

public interface FieidGetter {

public void setObj ect(Object o) О throws IiiegaiArgumentException;

pubiic Object getFieid(String fieidName) e throws IiiegaiAccessException;


pubiic ciass RefiectionFieidGetter impiements FieidGetter { static LocaiStrings is =


protected Object o;

public void setObject(Object o) О throws IllegalArgumentException


this.o = o;


public Object getField(String fieldName) О throws IllegalAccessException


try {

return BeanUtil.getObjectPropertyValue(o,


null); О

} catch(InvocationTargetException ex) {

} catch(IllegalAccessException ex) {

} catch(IntrospectionException ex) {

} catch(NoSuchMethodException ex) {


// Throw an exception



О Generic method to set the object whose fields we ’ll later retrieve.
e Generic method to get an object’s field by name.
e For ReflectionFieldGetter, setobject will be set with a JavaBean.
О For ReflectionFieldGetter, getField uses reflection (seen in chapter 8) to get a field from the JavaBean.

FieldGetter has two methods: setObject() that tells the getter which object we are going to query for a field and getField() to procure the field’s value. When using a FieldGetter, instantiate it, then set an object into the FieldGetter using setObject(), and then call getField() to get the values of the wanted fields. For error notification, FieldGetter’s methods can throw exceptions (e.g., if the object set into the FieldGetter implementation is not of the right type, say a ResultSet for a database-aware FieldGetter). To further clarify FieldGetter, listing 10.15 also shows the implementation of ReflectionFieldGetter which implements the FieldGetter functionality for JavaBeans by using the reflection API. Remembering the types of objects IterateTag enumerates, it is reasonable to assume that it is going to step over beans in its iterations.

Скачать в pdf «JSP Tag Libraries»