提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
通过反射按参数类型查找正确的方法
//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;