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

获取Java Bean简单属性读取方法

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

527
获取Java Bean简单属性读取方法


//package com.nowjava;
/**
来 自 nowjava.com - 时  代  Java
**/

import java.beans.BeanInfo;


import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;


import java.lang.reflect.Method;


public class Main {

    public static Method getSimplePropertyReadMethod(Object bean,

            String name) {

        PropertyDescriptor propertyDescriptor = getPropertyDescriptor(bean,

                name);

        if (propertyDescriptor == null)

            throw new IllegalArgumentException("No property:" + name);
            /**
             from
            * 时代Java公众号 - nowjava.com 
            **/

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