集册 Java实例教程 检索命名的bean属性值。

检索命名的bean属性值。

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

420
检索命名的bean属性值。

/*

 * Hibernate, Relational Persistence for Idiomatic Java

 *

 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.

 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.

 */// from n o w j a   v  a . c o m - 时  代  Java

//package com.nowjava;

import java.lang.reflect.Field;

import java.lang.reflect.Method;


public class Main {



    /**

     * Retrieve a named bean property value.

     *

     * @param bean The bean instance

     * @param propertyName The name of the property whose value to extract

     *

     * @return the property value

     */

    public static Object getBeanProperty(Object bean, String propertyName) {

        validateArgs(bean, propertyName);


        // try getters first

        final Method getter = getMethod(bean, propertyName);

        if (getter != null) {

            try {

                return getter.invoke(bean);

            } catch (Exception e) {

                /**/
                /**
                来 自 时代Java - N o w  J a v a . c o m
                **/

            }

        }


        // then try fields

        final Field field = getField(bean, propertyName);

        if (field != null) {

            try {

                field.setAccessible(true);

                return field.get(bean);

            } catch (Exception e) {

                /**/

            }

        }


        return null;

    }


    private static void validateArgs(Object bean, String propertyName) {

        if (bean == null) {

            throw new IllegalArgumentException("bean is null");

        }

        if (propertyName == null) {

            throw new IllegalArgumentException("propertyName is null");

        }

        if (propertyName.trim().length() == 0) {

            throw new IllegalArgumentException("propertyName is empty");

        }

    }


    /**

     * Return the named getter method on the bean or null if not found.

     *

     * @param bean The bean

     * @param propertyName The property to get the getter for

     *

     * @return the named getter method

     */

    private static Method getMethod(Object bean, String propertyName) {

        final StringBuilder sb = new StringBuilder("get").append(Character

                .toUpperCase(propertyName.charAt(0)));

        if (propertyName.length() > 1) {

            sb.append(propertyName.substring(1));

        }

        final String getterName = sb.toString();

        for (Method m : bean.getClass().getMethods()) {

            if (getterName
展开阅读全文