Here you can find the source of getMethod(Class> declaringType, String methodName, Class>... parameterTypes)
Parameter | Description |
---|---|
declaringType | the name of the class |
methodName | the name of the method to look for |
parameterTypes | the types of the parameters |
public static Method getMethod(Class<?> declaringType, String methodName, Class<?>... parameterTypes)
//package com.java2s; /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License./* w ww .j a v a 2 s .c o m*/ */ import java.lang.reflect.Method; public class Main { /** * Finds a method by name and parameter types. * * @param declaringType the name of the class * @param methodName the name of the method to look for * @param parameterTypes the types of the parameters */ public static Method getMethod(Class<?> declaringType, String methodName, Class<?>... parameterTypes) { return findMethod(declaringType, methodName, parameterTypes); } private static Method findMethod(Class<? extends Object> clazz, String methodName, Object[] args) { for (Method method : clazz.getDeclaredMethods()) { // TODO add parameter matching if (method.getName().equals(methodName) && matches(method.getParameterTypes(), args)) { return method; } } Class<?> superClass = clazz.getSuperclass(); if (superClass != null) { return findMethod(superClass, methodName, args); } return null; } private static boolean matches(Class<?>[] parameterTypes, Object[] args) { if ((parameterTypes == null) || (parameterTypes.length == 0)) { return ((args == null) || (args.length == 0)); } if ((args == null) || (parameterTypes.length != args.length)) { return false; } for (int i = 0; i < parameterTypes.length; i++) { if ((args[i] != null) && (!parameterTypes[i].isAssignableFrom(args[i].getClass()))) { return false; } } return true; } }