集册 Java实例教程 通过反射按参数类型查找正确的方法

通过反射按参数类型查找正确的方法

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

390
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
通过反射按参数类型查找正确的方法


//package com.nowjava;


import java.lang.reflect.Method;/**from N o  w  J a v a . c o m - 时  代  Java**/

import java.util.List;


public class Main {

    public static void main(String[] argv) throws Exception {

        Class clazz = String.class;

        List types = java.util.Arrays.asList("asdf", "nowjava.com");

        String methodName = "nowjava.com";

        System.out.println(findProperMethod(clazz, types, methodName));

    }


    public static Method findProperMethod(Class<?> clazz,

            List<Class<?>> types, String methodName) {

        Method[] methods = clazz.getMethods();/** 时代Java - N o w  J a v a . c o m 提供 **/


        for (Method method : methods) {

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

                    && isProperMethod(method, types)) {

                return method;

            }

        }


        return null;

    }


    protected static boolean isProperMethod(Method method,

            List<Class<?>> types) {

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


        if (methodParams.length != types.size()) {

            return false;

展开阅读全文