集册 Java实例教程 在Bean上返回命名的getter方法,如果找不到,则返回null。

在Bean上返回命名的getter方法,如果找不到,则返回null。

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

520
在Bean上返回命名的getter方法,如果找不到,则返回null。

/*

 * 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 时代Java公众号 - N o w J a  v a . c o m 
 */

//package com.nowjava;


import java.lang.reflect.Method;


public class Main {



    /**

     * 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();/* 来自 时代Java - N o w  J a v a . c o m*/

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

  
展开阅读全文