通过制定方法名 和方法参数 从类中查找方法

    protected Method findMatchingMethod() {
        String targetMethod = getTargetMethod();
        Object[] arguments = getArguments();
        int argCount = arguments.length;

        Method[] candidates = ReflectionUtils.getAllDeclaredMethods(getTargetClass());
        int minTypeDiffWeight = Integer.MAX_VALUE;
        Method matchingMethod = null;

        for (Method candidate : candidates) {
            if (candidate.getName().equals(targetMethod)) {
                Class[] paramTypes = candidate.getParameterTypes();
                if (paramTypes.length == argCount) {
                    int typeDiffWeight = getTypeDifferenceWeight(paramTypes, arguments);
                    if (typeDiffWeight < minTypeDiffWeight) {
                        minTypeDiffWeight = typeDiffWeight;
                        matchingMethod = candidate;
                    }
                }
            }
        }

        return matchingMethod;
    }

 

 

    public static int getTypeDifferenceWeight(Class[] paramTypes, Object[] args) {
        int result = 0;
        for (int i = 0; i < paramTypes.length; i++) {
            if (!ClassUtils.isAssignableValue(paramTypes[i], args[i])) {
                return Integer.MAX_VALUE;
            }
            if (args[i] != null) {
                Class paramType = paramTypes[i];
                Class superClass = args[i].getClass().getSuperclass();
                while (superClass != null) {
                    if (paramType.equals(superClass)) {
                        result = result + 2;
                        superClass = null;
                    }
                    else if (ClassUtils.isAssignable(paramType, superClass)) {
                        result = result + 2;
                        superClass = superClass.getSuperclass();
                    }
                    else {
                        superClass = null;
                    }
                }
                if (paramType.isInterface()) {
                    result = result + 1;
                }
            }
        }
        return result;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值