find Method by method name and parameters - Android java.lang.reflect

Android examples for java.lang.reflect:Method

Description

find Method by method name and parameters

Demo Code


//package com.java2s;

import java.lang.reflect.Method;

public class Main {
    public static Method findMethod(Class<?> clazz, String name,
            Class<?>[] paramTypes) {
        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            if (name.equals(method.getName())
                    && paramTypes.length == method.getParameterTypes().length) {
                boolean found = true;
                Class<?>[] methodParameterTypes = method
                        .getParameterTypes();
                for (int j = 0; j < methodParameterTypes.length; j++) {
                    found = methodParameterTypes[j]
                            .isAssignableFrom(paramTypes[j]);
                    if (!found) {
                        break;
                    }/*ww w  .j  ava  2  s. co m*/
                }

                if (found) {
                    method.setAccessible(true);
                    return method;
                }
            }
        }
        return null;
    }
}

Related Tutorials