package mypackage;
import java.lang.reflect.*;
/**
* Implementation of a DocumentBuilder that extracts the data
* needed to support the getValue method from the Object
* provided in the constructor. The field codes it expects
* must be the name of a method that accepts no arguments.
**/
public class ObjectDocumentBuilder extends DocumentBuilder {
private Object model = null;
/**
* Creates a new instance using the Object parameter as the "data"
* source, and the template as the document template.
**/
public ObjectDocumentBuilder(Object model, String template){ // Line 18
super(template); // Line 19
this.model = model; // Line 20
} // Line 21
/**
* returns String value representing data associated with field code.
* in this implementation, the field code is the name of a method that
* we will call on the Object model. It is assumed that the Object
* model has a no argument implementation of this method. If the object
* does not have an no argument method by the same name as the fieldCode
* value, then <code>null</code> is returned.
**/
public String getValue(String fieldCode) {
Method method;
Object[] args = {};
Class[] params = {};
String val = null;
try{
// use reflection to access the method by name
// and invoke it to retrieve its return value
method = model.getClass().getMethod(fieldCode, params); // Line 40
val = method.invoke(model, args).toString(); // Line 41
}
catch(Exception e){
// something happened when trying to invoke the method.
// we'll assume the method doesn't exist and continue
// using a null value
val = null;
}
finally{
// return whatever value we have come up with
return val;
}
}
}
End of Listing