集册 Java实例教程 获取Java Bean简单属性

获取Java Bean简单属性

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

414
获取Java Bean简单属性
/**n o w j a v a . c o m - 时  代  Java**/


//package com.nowjava;

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)
    /*
     from 时 代 J     a    v  a - nowjava.com 
    */

            throws IllegalArgumentException, IllegalAccessException,

            InvocationTargetException {

        Method readMethod = getSimplePropertyReadMethod(bean, name);

        if (readMethod == null)

            throw new IllegalArgumentException(

                    "No readMethod for property:" + name);

        readMethod.setAccessible(true);

        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) {

        
展开阅读全文