本文转载自:http://www.cnblogs.com/tclee/archive/2012/02/28/2012773.html
在上面这篇文档中,作者使用了Java jdk中的反射来调用set方法。
个人愚见:如果是javaBean的话,我们可以使用内省来操作属性,jdk中提供了:
java.beans.Introspector和java.beans.PropertyDescriptor来进行内省操作
private static void setProperties(Object pt1, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodSetX = pd2.getWriteMethod();
methodSetX.invoke(pt1,value);
}
private static Object getProperty(Object pt1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
/*PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodGetX = pd.getReadMethod();
Object retVal = methodGetX.invoke(pt1);*/
BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = null;
for(PropertyDescriptor pd : pds){
if(pd.getName().equals(propertyName))
{
Method methodGetX = pd.getReadMethod();
retVal = methodGetX.invoke(pt1);
break;
}
}
return retVal;
}
另外,我们也可以使用Apache提供的给我们的BeanUtils和PropertyUtils来进行内省操作
org.apache.commons.beanutils.PropertyUtils.setProperty(Object bean, String name, Object value)
sorg.apache.commons.beanutils.BeanUtils.etProperty(Object bean, String name, Object value)