find Proper Method by parameter type via reflection - Java Reflection

Java examples for Reflection:Method Parameter

Description

find Proper Method by parameter type via reflection

Demo Code


//package com.java2s;

import java.lang.reflect.Method;
import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        List types = java.util.Arrays.asList("asdf", "java2s.com");
        String methodName = "java2s.com";
        System.out.println(findProperMethod(clazz, types, methodName));
    }/*from  w ww. jav  a 2  s  .  c  om*/

    public static Method findProperMethod(Class<?> clazz,
            List<Class<?>> types, String methodName) {
        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            if (methodName.equals(method.getName())
                    && isProperMethod(method, types)) {
                return method;
            }
        }

        return null;
    }

    protected static boolean isProperMethod(Method method,
            List<Class<?>> types) {
        Class<?>[] methodParams = method.getParameterTypes();

        if (methodParams.length != types.size()) {
            return false;
        }

        for (int i = 0; i < types.size(); ++i) {
            if (!methodParams[i].isAssignableFrom(types.get(i))) {
                return false;
            }
        }
        return true;
    }
}

Related Tutorials