标签:object void 常用 stat for getbean 反射 throwable set
The Introspector class provides a standard way for tools to learn about the properties, events, and methods supported by a target Java Bean.
Introspector提供了一种标准的方式作为工具来获取类的属性,时间,方法。
// 类属性缓存,空间换时间private static final ConcurrentMap, PropertyDescriptor[]> classPropCache =new ConcurrentHashMap, PropertyDescriptor[]>(64);/*** 获取Bean的属性* @param bean* @return*/private static PropertyDescriptor[] getPropertyDescriptors(Object bean) {Class beanClass = bean.getClass();PropertyDescriptor[] cachePds = classPropCache.get(beanClass);if (null != cachePds) {return cachePds;}try {BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);cachePds = beanInfo.getPropertyDescriptors();classPropCache.put(beanClass, cachePds);return cachePds;} catch (IntrospectionException e) {throw new RuntimeException(e);}}/*** 获取Bean的属性* @param bean bean* @param propertyName 属性名* @return 属性值*/public static Object getProperty(Object bean, String propertyName) {PropertyDescriptor[] beanPds = getPropertyDescriptors(bean);for (PropertyDescriptor propertyDescriptor : beanPds) {if (propertyDescriptor.getName().equals(propertyName)){Method readMethod = propertyDescriptor.getReadMethod();if (null == readMethod) {continue;}if (!readMethod.isAccessible()) {readMethod.setAccessible(true);}try {return readMethod.invoke(bean);} catch (Throwable ex) {throw new RuntimeException("Could not read property ‘" + propertyName + "‘ from bean", ex);}}}return null;}/*** 设置Bean属性* @param bean bean* @param propertyName 属性名* @param value 属性值*/public static void setProperty(Object bean, String propertyName, Object value) {PropertyDescriptor[] beanPds = getPropertyDescriptors(bean);for (PropertyDescriptor propertyDescriptor : beanPds) {if (propertyDescriptor.getName().equals(propertyName)){Method writeMethod = propertyDescriptor.getWriteMethod();if (null == writeMethod) {continue;}if (!writeMethod.isAccessible()) {writeMethod.setAccessible(true);}try {writeMethod.invoke(bean, value);} catch (Throwable ex) {throw new RuntimeException("Could not set property ‘" + propertyName + "‘ to bean", ex);}}}}
标签:object void 常用 stat for getbean 反射 throwable set
原文地址:http://www.cnblogs.com/LiuChunfu/p/6624732.html