Java Reflection Method Return getMethod(Class clazz, String methodName, Class returnType, Class... inputParams)

Here you can find the source of getMethod(Class clazz, String methodName, Class returnType, Class... inputParams)

Description

get Method

License

Open Source License

Declaration

public static Method getMethod(Class<?> clazz, String methodName, Class<?> returnType,
            Class<?>... inputParams) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 Robert "Unlogic" Olofsson (unlogic@unlogic.se).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v3
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-3.0-standalone.html
 ******************************************************************************/

import java.lang.reflect.Method;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static Method getMethod(Class<?> clazz, String methodName, Class<?> returnType,
            Class<?>... inputParams) {

        if (inputParams == null) {

            inputParams = new Class<?>[0];
        }/*from  w w w.j a v  a2 s  .  c  o m*/

        Method[] methods = clazz.getDeclaredMethods();

        for (Method method : methods) {

            if (method.getName().equals(methodName) && returnType.isAssignableFrom(method.getReturnType())
                    && Arrays.equals(inputParams, method.getParameterTypes())) {

                return method;
            }
        }

        return null;
    }

    public static Method getMethod(Class<?> clazz, String methodName, int argumentCount) {

        List<Method> methods = getMethods(clazz);

        for (Method method : methods) {

            if (!method.getName().equalsIgnoreCase(methodName)) {

                continue;
            }

            if (method.getParameterTypes().length != argumentCount) {

                continue;
            }

            return method;
        }

        return null;
    }

    public static List<Method> getMethods(Class<?> clazz) {

        ArrayList<Method> methods = new ArrayList<Method>();

        methods.addAll(Arrays.asList(clazz.getDeclaredMethods()));

        clazz = clazz.getSuperclass();

        while (clazz != Object.class) {

            methods.addAll(Arrays.asList(clazz.getDeclaredMethods()));

            clazz = clazz.getSuperclass();
        }

        return methods;
    }
}

Related

  1. getMethod(Class clazz, String name, String returnType, String[] args)
  2. getMethod(Class parentClass, Class returnType, String methodName, Class... types)
  3. getMethod(Class type, String name, Class returnType, Class paramType, boolean caseSensitive)
  4. getMethodByReturnType(final Class source, final Class type)