(一)内省 Introspector /** * 用于操作javabean(特殊的java类:get/set) */ class MyBeanUtils{ //1. 反射操作bean public static Object getProperties1(Object bean, String name) throws Exception{ Field f = bean.getClass().getDeclaredField(name); f.setAccessible(true); return f.get(bean); } public static void setProperties1(Object bean, String name, Object value) throws Exception{ Field f = bean.getClass().getDeclaredField(name); f.setAccessible(true); f.set(bean, value); } //2. 内省操作bean,复杂方式 public static Object getProperties2(Object bean, String name) throws Exception{ BeanInfo info = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] pds = info.getPropertyDescriptors(); for(PropertyDescriptor pd: pds){ if(pd.getName().equals(name)){ return pd.getReadMethod().invoke(bean); } } return null; } public static void setProperties2(Object bean, String name, Object value) throws Exception{ BeanInfo info = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] pds = info.getPropertyDescriptors(); for(PropertyDescriptor pd: pds){ if(pd.getName().equals(name)){ pd.getWriteMethod().invoke(bean, value); } } } //3. 内省操作bean,简单方式 public static Object getProperties3(Object bean, String name) throws Exception{ PropertyDescriptor pd = new PropertyDescriptor(name, bean.getClass()); Method get = pd.getReadMethod(); return get.invoke(bean); } public static void setProperties3(Object bean, String name, Object value) throws Exception{ PropertyDescriptor pd = new PropertyDescriptor(name, bean.getClass()); Method set = pd.getWriteMethod(); set.invoke(bean, value); } }
|