Java examples for Reflection:Java Bean
set a bean's property, the Class of the property must be the same as the Class of v;
/**/*from w w w . ja v a2s. c om*/ *all rights reserved,@copyright 2003 */ import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; public class Main{ public static void main(String[] argv) throws Exception{ Object bean = "java2s.com"; String propertyName = "java2s.com"; Object v = "java2s.com"; setBeanProperty(bean,propertyName,v); } 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 Method getMethod(Object o, String methodName, Class[] paramTypes) throws NoSuchMethodException { Class clz = o.getClass(); return clz.getMethod(methodName, paramTypes); } /** * * * @param clz * @param methodName * @param paramTypes * @return * @throws NoSuchMethodException */ public static Method getMethod(Class clz, String methodName, Class[] paramTypes) throws NoSuchMethodException { return clz.getMethod(methodName, paramTypes); } }