Java Reflection Method Get from Object getMethod(Object o, String methodName, Class[] args)

Here you can find the source of getMethod(Object o, String methodName, Class[] args)

Description

get Method

License

Open Source License

Declaration

static public Method getMethod(Object o, String methodName, Class<?>[] args) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Method;

public class Main {
    static public Method getMethod(Object o, String methodName, Class<?>[] args) {
        return getMethod(o.getClass(), methodName, args);
    }//from www.j  a  va2s.c o m

    static public Method getMethod(Class<?> clazz, String methodName, Class<?>[] args) {
        return getMethod(clazz, methodName, args, false);
    }

    static public Method getMethod(Class<?> clazz, String methodName, Class<?>[] args,
            boolean includePrivateMethods) {
        Method[] methods = null;

        // with Class.getDeclaredMethods(), private methods of the class are
        // also returned.
        // but the inherited methods are not returned which we get with
        // getMethods()
        if (includePrivateMethods)
            methods = clazz.getDeclaredMethods();
        else
            methods = clazz.getMethods();

        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals(methodName) == false)
                continue;

            Class<?>[] declaredArgs = methods[i].getParameterTypes();
            if (declaredArgs == null || declaredArgs.length == 0) {
                if (args == null)
                    return methods[i];
                continue;
            }

            if (args == null || declaredArgs.length != args.length)
                continue;

            boolean allArgsAssignable = true;
            for (int j = 0; j < declaredArgs.length; j++) {
                if (declaredArgs[j].isAssignableFrom(args[j]) == false) {
                    allArgsAssignable = false;
                    break;
                }
            }

            if (allArgsAssignable)
                return methods[i];
        }

        return null;
    }
}

Related

  1. getMethod(final String methodName, final Object obj, final Class... argTypes)
  2. getMethod(Object bean, String propertyName)
  3. getMethod(Object instance, String methodName, Class... argsClass)
  4. getMethod(Object instance, String methodName, Class[] parameters)
  5. getMethod(Object o, String methodName)
  6. getMethod(Object o, String methodName, Class[] paramTypes)
  7. getMethod(Object obj, Class[] paramTypes, String methodName)
  8. getMethod(Object obj, String fieldName)
  9. getMethod(Object obj, String methodName)