看完这一节之后,听张老师说做开发的时候对JavaBean的内省操作使用的很频繁- private static void setProperties(Object pt, String propertyName,Object value)
- throws IntrospectionException, IllegalAccessException,
- InvocationTargetException {
- PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt.getClass());
-
- Method methodSetX = pd.getWriteMethod();
-
- methodSetX.invoke(pt, value);
- }
- private static Object getProperties(Object pt,
- String propertyName) throws IntrospectionException,
- IllegalAccessException, InvocationTargetException {
- //PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt.getClass());
-
- //Method methodGetX = pd.getReadMethod();
-
- //Object retVal = methodGetX.invoke(pt);
- BeanInfo beaninfo = Introspector.getBeanInfo(pt.getClass());
-
- PropertyDescriptor[] pds = beaninfo.getPropertyDescriptors();
-
- Object retVal = null;
-
- for(PropertyDescriptor pd:pds){
- if(pd.getName().equals(propertyName)){
- Method methodGetX = pd.getReadMethod();
- retVal = methodGetX.invoke(pt);
- break;
- }
- }
-
- return retVal;
- }
复制代码 我想问的是当我们要获取或者修改JavaBean的属性值时,为什么不直接用对象调用get或set方法呢,内省操作的好处是什么? |