集册 Java实例教程 通过名称获取Java Bean属性

通过名称获取Java Bean属性

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

544
通过名称获取Java Bean属性


import java.beans.BeanInfo;

import java.beans.IndexedPropertyDescriptor;

import java.beans.IntrospectionException;//from 时 代      J a v a   公   众 号 - nowjava.com

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.Collections;

import java.util.Map;

import java.util.TreeMap;


public class Main{

    public static void main(String[] argv) throws Exception{

        Object bean = "nowjava.com";

        String name = "nowjava.com";

        System.out.println(getProperty(bean,name));

    }

    public static Object getProperty(Object bean, String name)

            throws NoSuchMethodException, IllegalArgumentException,

            IllegalAccessException, InvocationTargetException,

            IntrospectionException {
            /* 
            *来 自
             nowjava - 时  代  Java
            */

        Debug.isNotNull("bean", bean);

        final Class<?> clazz = bean.getClass();

        final PropertyDescriptor pd = BeanHelper.getPropertyDescriptor(

                clazz, name);

        if (pd == null) {

            final String msg = BeanHelper.getNoSuchPropertyMessage(name,

                    clazz);

            throw new NoSuchMethodException(msg);

        } else if (pd instanceof IndexedPropertyDescriptor) {

            final String msg = BeanHelper.getUnsupportedPropertyMessage(

                    name, clazz);

            throw new IllegalArgumentException(msg);

        }

        Method getter = pd.getReadMethod();

        if (getter == null) {

            final String msg = BeanHelper.getNoSuchPropertyMessage(name,

                    clazz);

            throw new NoSuchMethodException(msg);

        }

        return getter.invoke(bean, (Object[]) null);

    }

    public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz,

            String name) throws IntrospectionException {

        final PropertyDescriptor[] array = BeanHelper

                .getPropertyDescriptors(clazz);

        for (int i = 0, n = array.length; i < n; ++i) {

            if (array[i].getName().equals(name)) {

                return array[i];

            }

        }

        return null;

    }

    protected static String getNoSuchPropertyMessage(String name,

            Class<?> clazz) {

        return "could not find poperty=" + name + " of class="

                + (clazz != null ? clazz.getCanonicalName() : null);

    }

    protected 
展开阅读全文