import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 使用内省的方式操作JavaBean */ public class IntroSpectorTest { public static void main(String[] args) throws Exception { ReflectPoint reflectPoint = new ReflectPoint(3,7); //调用JavaBean中方法的传统作法 Class classz = reflectPoint.getClass(); Field[] fields = classz.getDeclaredFields(); for (Field field : fields) { String name = "set" + field.getName().toUpperCase(); Method method = classz.getMethod(name, int.class); method.invoke(reflectPoint, 3); } System.out.println(reflectPoint); //使用内省的方式调用JavaBean的方法 String propertyName = "x"; //获得属性x的值 Object retVal = getProperty2(reflectPoint, propertyName); System.out.println(retVal); //设置属性x的值 setProperty(reflectPoint, propertyName,10); System.out.println(reflectPoint.getX()); } /** * 设置属性的值 * @param obj 属性所属的对象 * @param propertyName 属性名 * @param propertyValue 属性值 */ private static void setProperty(Object obj, String propertyName,Object propertyValue) throws Exception { PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,obj.getClass()); Method setMethod = pd2.getWriteMethod(); setMethod.invoke(obj, propertyValue); } /** * 获得对象的属性值 * @param obj 属性所属的对象 * @param propertyName 属性名 * @return 属性的值 */ private static Object getProperty(Object obj, String propertyName) throws Exception { PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass()); Method getMethod = pd.getReadMethod(); //获得get方法 Object retVal = getMethod.invoke(obj); return retVal; } /** * 使用内省操作javabean * @param obj 属性所属的对象 * @param propertyName 属性名 * @return 属性的值 */ private static Object getProperty2(Object obj, String propertyName) throws Exception { Object retVal = null; BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (pd.getName().equals(propertyName)) { Method getMethod = pd.getReadMethod(); retVal = getMethod.invoke(obj); break; } } return retVal; } }