javaBean-1
import java.beans.IntrospectionException;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class IntroSpectorTest { public static void main(String[] args) throws Exception{ ReflectPoint1 pt1 = new ReflectPoint1(3,5); String propertyName = "x"; Object retval = getProperty(pt1, propertyName); System.out.println(retval); Object value = 7; setProperty(pt1, propertyName, value); } private static void setProperty(Object pt1, String propertyName, Object value) throws IntrospectionException, IllegalAccessException, InvocationTargetException { PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, pt1.getClass()); //propertyName为字段名 //javaBean的操作方式 Method methodSetx = pd2.getWriteMethod(); //调用该字段的setxxx方法 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();//调用该字段的getxxxx方法 Object retval = methodGetX.invoke(pt1); return retval; }}
private static Object getProperty(Object pt1, String propertyName) throws IntrospectionException, IllegalAccessException, InvocationTargetException { /* PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass()); Method methodGetX = pd.getReadMethod();//调用该字段的getxxxx方法 Object retval = methodGetX.invoke(pt1); return retval; */ 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; }