集册 Java实例教程 获取方法最佳匹配

获取方法最佳匹配

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

617
获取方法最佳匹配


//package com.nowjava;//时 代 J a v a - N o w J a v a . c o m


import java.lang.reflect.Method;

import java.util.HashMap;


public class Main {

    private static HashMap<String, Method> sMethodCache = new HashMap<String, Method>();

    private static HashMap<Class<?>, Class<?>> primativeClassMap = new HashMap<Class<?>, Class<?>>();


    private static Method getMethodBestMatch(Class<?> clazz,

            String methodName, Class<?>... argClasses) throws Throwable {

        String methodFullName = genMethodFullName(clazz, methodName,

                argClasses);

        if (sMethodCache.containsKey(methodFullName))/** 来 自 nowjava - 时代Java**/

            return sMethodCache.get(methodFullName);

        for (Method method : clazz.getDeclaredMethods()) {

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

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

                if (compareArgs(tmpArgs, argClasses)) {

                    method.setAccessible(true);

                    sMethodCache.put(methodFullName, method);

                    return method;

                }

            }

        }

        String msg = "";

        for (Class<?> cls : argClasses) {

            msg += cls.getSimpleName() + ",";

        }

        msg = "Can't get method: " + clazz.getSimpleName() + "."

                + methodName + "(" + msg + ")";

        throw new Exception(msg);

    }


    private static String genMethodFullName(Class<?> clazz,

            String methodName, Class<?>... argClasses) {

        StringBuilder name = new StringBuilder();

        name.append(clazz.getName());

        name.append(":");

        name.append(methodName);

        for (int i = 0; i < argClasses.length; i++) {

            if (i == (argClasses.length - 1)) {

                name.append(argClasses[i].getName());

            } else {

                name.append(argClasses[i].getName());

                name.append(",");

            }

        }

        return name.toString();

    }


    private static boolean compareArgs(Class<?>[] dstArgs,

            Class<?>[] origArgs) {

        if (dstArgs.length != origArgs.length)

            return false;

        for (int i = 0; i < dstArgs.length; i++) {

            if (!isChildClass(dstArgs[i], origArgs[i]))

                return false;

        }

        return true;

    }


    private static boolean isChildClass(Class<?> origClass,

            Class<?> dstClass) {

        if (dstClass == null)

            return true;

        if (origClass.isInterface()) {

        
展开阅读全文