集册 Java实例教程 查找给定属性的对象获取方法。

查找给定属性的对象获取方法。

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

314
查找给定属性的对象获取方法。


//package com.nowjava;

import java.lang.reflect.Method;

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

public class Main {

    /**

     * Find the object getter method for the given property.

     * <p/>

     * If this method cannot find a 'get' property it tries to lookup an 'is'

     * property.

     *

     * @param object the object to find the getter method on

     * @param property the getter property name specifying the getter to lookup

     * @param path the full expression path (used for logging purposes)

     * @return the getter method

     */

    public final static Method findGetter(Object object, String property,

            String path) {


        // Find the getter for property

        String getterName = toGetterName(property);


        Method method = null;
        /*
        来 自*
         nowjava
        */

        Class sourceClass = object.getClass();


        try {

            method = sourceClass.getMethod(getterName, (Class[]) null);

        } catch (Exception e) {

        }


        if (method == null) {

            String isGetterName = toIsGetterName(property);

            try {

                method = sourceClass

                        .getMethod(isGetterName, (Class[]) null);

            } catch (Exception e) {

                StringBuilder buffer = new StringBuilder();

                buffer.append("Result: neither getter methods '");

                buffer.append(getterName).append("()' nor '");

                buffer.append(isGetterName).append(

                        "()' was found on class: '");

                buffer.append(object.getClass().getName()).append("'.");

                throw new RuntimeException(buffer.toString(), e);

            }

        }

        return method;

    }


    /**

     * Return the getter method name for the given property name.

     *

     * @param property the property name

     * @return the getter method name for the given property name.

     */

    public static String toGetterName(String property) {

        StringBuilder buffer = new StringBuilder(property.length() + 3);


        buffer.append("get");

        buffer.append(Character.toUpperCase(property.charAt(0)));

        buffer.append(property.substring(1));


        return buffer.toString();

    }


    
展开阅读全文