集册 Java实例教程 为给定的源对象和目标对象调用setter方法。

为给定的源对象和目标对象调用setter方法。

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

462
为给定的源对象和目标对象调用setter方法。


//package com.nowjava;

import java.lang.reflect.Method;

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

public class Main {

    /**

     * Invoke the setter method for the given source and target object.

     *

     * @param setterMethod the setter method to invoke

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

     * @param target the target object to set

     * @param property the setter method property name (used for logging)

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

     */

    public final static void invokeSetter(Method setterMethod,

            Object source, Object target, String property, String path) {


        try {

            Object[] objectArgs = { target };

            setterMethod.invoke(source, objectArgs);

            /*
            来 自*
             时 代      J a v a   公   众 号 - nowjava.com
            */

        } catch (Exception e) {

            // Log detailed error message of why setter failed

            StringBuilder buffer = new StringBuilder();

            buffer.append("Result: error occurred while trying to set an");

            buffer.append(" instance of '");

            buffer.append(target.getClass().getName()).append(

                    "' using method '");

            buffer.append(setterMethod.getName()).append("(");

        
展开阅读全文