设置bean的属性时,该属性的Class必须与v的Class相同;
/** *all rights reserved,@copyright 2003 */ import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; /* N o w J a v a . c o m 提 供 */ import java.util.HashMap; public class Main{ public static void main(String[] argv) throws Exception{ Object bean = "nowjava.com"; String propertyName = "nowjava.com"; Object v = "nowjava.com"; setBeanProperty(bean,propertyName,v); /* 来自 *N o w J a v a . c o m - 时代Java*/ } public static final String PROPERTY_SET_METHOD_PREFIX = "set"; /** * set a bean's property, the Class of the property must be the same as the Class * of v; * * @param bean the target bean object; * @param propertyName the property name; * @param v the property value; * @throws com.cots.bean.NoSuchPropertyException if the bean has no this property; * @throws SetPropertyException if has no acceess to this property,or nested Exception is thrown when * call the setMethod */ public static void setBeanProperty(Object bean, String propertyName, Object v) throws NoSuchPropertyException, SetPropertyException { Class propertyClass = v.getClass(); setBeanProperty(bean, propertyName, propertyClass, v); } /** * set a bean's property. * * @param bean the target bean object; * @param propertyName the property name; * @param propertyClass the Class of the property; * @param v the property value; * @throws NoSuchPropertyException if the bean has no this property; * @throws com.cots.bean.SetPropertyException if has no acceess to this property,or nested Exception is thrown when * call the setMethod */ public static void setBeanProperty(Object bean, String propertyName, Class propertyClass, Object v) throws NoSuchPropertyException, SetPropertyException { String methodName = BeanUtil.PROPERTY_SET_METHOD_PREFIX + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); Class[] clz = new Class[1]; clz[0] = propertyClass; try { Method m = getMethod(bean, methodName, clz); m.invoke(bean, new Object[] { v }); } catch (NoSuchMethodException e) { throw new NoSuchPropertyException(bean.getClass().getName(), propertyName, propertyClass.getName()); } catch (IllegalAccessException e) { throw new SetPropertyException("illegal access to property:" + propertyName); } catch (InvocationTargetException e) { throw new SetPropertyException(e.getTargetException() .getMessage()); } } /** * * * @param o * @param methodName * @param paramTypes * @return * @throws NoSuchMethodException */ public static