Java examples for Reflection:Method Return
find method: All args must be supplied, if any args are null then this method returns null.
//package com.java2s; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class Main { /**//from ww w. j a va 2 s . co m * All args must be supplied, if any args are null then this method returns null. * * @param type * @param methodName * @param parameterTypes * @param resultType * @return */ public static Method findMethod(Class<?> type, String methodName, Class<?>[] parameterTypes, Class<?> resultType) { if (type == null || methodName == null || parameterTypes == null || resultType == null) return null; List<Method> compatibleMethods = new ArrayList<Method>(); for (Method method : type.getMethods()) { if (!methodName.equals(method.getName())) continue; if (!method.getReturnType().isAssignableFrom(resultType)) continue; Class<?>[] methodParameterTypes = method.getParameterTypes(); if (methodParameterTypes.length != parameterTypes.length) continue; boolean compatibleParameters = true; for (int parameterIndex = 0; parameterIndex < parameterTypes.length && compatibleParameters; ++parameterIndex) compatibleParameters |= methodParameterTypes[parameterIndex] .isAssignableFrom(parameterTypes[parameterIndex]); if (!compatibleParameters) continue; compatibleMethods.add(method); } return compatibleMethods.size() > 0 ? compatibleMethods.get(0) : null; } }