Java examples for Reflection:Java Bean
describe Java Bean
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; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Main{ public static void main(String[] argv) throws Exception{ Object obj = "java2s.com"; System.out.println(describe(obj)); }//from w ww . ja va 2 s . c om /** * @see #org.apache.commons.beanutils.PropertyUtils.describe(obj) */ public static Map describe(Object obj) { if (obj instanceof Map) return (Map) obj; Map map = new HashMap(); PropertyDescriptor[] descriptors = getPropertyDescriptors(obj .getClass()); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); Method readMethod = descriptors[i].getReadMethod(); if (readMethod != null) { try { map.put(name, readMethod.invoke(obj, new Object[] {})); } catch (Exception e) { GLogger.warn("error get property value,name:" + name + " on bean:" + obj, e); } } } return map; } public static PropertyDescriptor[] getPropertyDescriptors( Class beanClass) { BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(beanClass); } catch (IntrospectionException e) { return (new PropertyDescriptor[0]); } PropertyDescriptor[] descriptors = beanInfo .getPropertyDescriptors(); if (descriptors == null) { descriptors = new PropertyDescriptor[0]; } return descriptors; } public static PropertyDescriptor getPropertyDescriptors( Class beanClass, String name) { for (PropertyDescriptor pd : getPropertyDescriptors(beanClass)) { if (pd.getName().equals(name)) { return pd; } } return null; } }