集册 Java实例教程 查找方法:必须提供所有参数,如果任何参数为null,则此方法返回null。

查找方法:必须提供所有参数,如果任何参数为null,则此方法返回null。

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

397
查找方法:必须提供所有参数,如果任何参数为null,则此方法返回null。

/**
时 代 J a v a 公 众 号 - nowjava.com 提供 
**/

//package com.nowjava;


import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;


public class Main {

    /**

     * All args must be supplied, if any args are null then this method returns null.

     * 

     * @param type

     * @param methodName

     * @param parameterTypes

     * @param resultType

     * @return

     */

    public static Method findMethod(Class<?> type, String methodName,

            Class<?>[] parameterTypes, Class<?> resultType) {

        if (type == null || methodName == null || parameterTypes == null

                || resultType == null)

            return null;


        List<Method> compatibleMethods = new ArrayList<Method>();


        for (Method method : type.getMethods()) {//来 自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m

            if (!methodName.equals(method.getName()))

                continue;

            if (!method.getReturnType().isAssignableFrom(resultType))

                continue;


            Class<?>[] methodParameterTypes = method.getParameterTypes();

            if (methodParameterTypes.length != parameterTypes.length)

                continue;


            boolean compatibleParameters = true;

            for (int parameterIndex = 0; parameterIndex < parameterTypes.length

                    && compatibleParameters; ++parameterIndex)

                compatibleParameters |= methodParameterTypes[paramete
展开阅读全文