集册 Java实例教程 描述Java Bean

描述Java Bean

欢马劈雪     最近更新时间:2020-01-02 10:19:05

508
描述Java Bean
//N o w J a v a . c o m 提 供

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 = "nowjava.com";

        System.out.println(describe(obj));/** from n o w j a v a . c o m - 时代Java**/

    }

    /**

     * @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 = 
展开阅读全文