集册 Java实例教程 尝试在目标上执行方法,如果方法不存在,请尝试执行其父类(如果找不到),则不执行任何操作。

尝试在目标上执行方法,如果方法不存在,请尝试执行其父类(如果找不到),则不执行任何操作。

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

380
尝试在目标上执行方法,如果方法不存在,请尝试执行其父类(如果找不到),则不执行任何操作。


//package com.nowjava;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;/* 来自 时代Java公众号*/


public class Main {



    /**

     * try to execute a method on target, if method does not exist, try its parent class

     * if not found, do nothing. Dispatched methods may throw an exception.

     * @throws RuntimeException, if invoked method throws an exception, the thrown exception is given up by this function as a runtime exception

     * @throws IllegalAccessException, if dispatch failed because of reflection reasons

     */

    public static Object silentDispatch(final Object target,

            final String methodName, Object parameter)

            throws RuntimeException {

        Object result = null;


        Class<?> targetClass = target.getClass();
        /**来自 
         时 代 J a v a 公 众 号 - nowjava.com**/

        Class<?> parameterClass = parameter.getClass();


        while (targetClass != null) {

            try {

                Method method = target.getClass().getMethod(methodName,

                        parameterClass);

                result = method.invoke(target, parameter);

                break;

            } catch (NoSuchMethodException e) {

                targetClass = targetClass.getSuperclass();

            } catch (InvocationTargetException e) {

                throw new RuntimeException(e.getTargetException());

            } catch
展开阅读全文