Java examples for Reflection:Java Bean
get Java Bean Simple Property
//package com.java2s; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { public static Object getSimpleProperty(Object bean, String name) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Method readMethod = getSimplePropertyReadMethod(bean, name); if (readMethod == null) throw new IllegalArgumentException( "No readMethod for property:" + name); readMethod.setAccessible(true);//from w ww . j a v a2 s . c o m Object value = readMethod.invoke(bean, new Object[0]); return value; } public static Method getSimplePropertyReadMethod(Object bean, String name) { PropertyDescriptor propertyDescriptor = getPropertyDescriptor(bean, name); if (propertyDescriptor == null) throw new IllegalArgumentException("No property:" + name); return propertyDescriptor.getReadMethod(); } public static PropertyDescriptor getPropertyDescriptor(Object bean, String name) { PropertyDescriptor[] descriptors = getPropertyDescriptors(bean); for (int i = 0; i < descriptors.length; i++) { if (name.equals(descriptors[i].getName())) return descriptors[i]; } return null; } public static PropertyDescriptor[] getPropertyDescriptors(Object bean) { BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(bean.getClass()); } catch (IntrospectionException e) { return (new PropertyDescriptor[0]); } PropertyDescriptor[] descriptors = beanInfo .getPropertyDescriptors(); return descriptors; } }