集册 Java实例教程 查找给定属性的源对象设置方法。

查找给定属性的源对象设置方法。

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

538
查找给定属性的源对象设置方法。


//package com.nowjava;/* 来 自 时代Java公众号 - N o w J a  v a . c o m*/

import java.lang.reflect.Method;


public class Main {

    /**

     * Find the source object setter method for the given property.

     *

     * @param source the source object to find the setter method on

     * @param property the property which setter needs to be looked up

     * @param targetClass the setter parameter type

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

     * @return the setter method

     */

    public final static Method findSetter(Object source, String property,

            Class targetClass, String path) {

        Method method = null;


        // Find the setter for property

        String setterName = toSetterName(property);


        Class sourceClass = source.getClass();

        Class[] classArgs = { targetClass };

        try {/* 来 自 nowjava.com*/

            method = sourceClass.getMethod(setterName, classArgs);

        } catch (Exception e) {

            // Log detailed error message of why setter lookup failed

            StringBuilder buffer = new StringBuilder();

            buffer.append("Result: setter method '");

            buffer.append(setterName).append("(")

                    .append(targetClass.getName());

            buffer.append(")' was not found on class '");

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

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

        }

        return method;

    }


    /**

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

     *

     * @param property the property name

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

     */

    public 
展开阅读全文