星期二, 三月 02, 2004

如何在Servlet 利用Java Reflection 机制来实现 提交的FormBean

/**
* Iterate through the setters of this object and then take the named
* parameters that match and set the value of the setter
* to the value of the corresponding parameter
*/
public void mapBean(javax.servlet.http.HttpServletRequest req, Object bean) {
Method[] methods = bean.getClass().getMethods();
for (int i=0; iMethod meth = methods[i];
if (meth.getName().startsWith("set")) {
String propertyName = meth.getName().substring(3).toUpperCase();
// matching without case is faster than matching with case
String parm = req.getParameter(propertyName);
if (parm != null) {
Object[] objs = new Object[1];
objs[0] = parm;
try {
meth.invoke(bean, objs);
} catch (Exception e) {} // could not set
}
}
}
}