Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore case-sensitive "methodName" for getting a method of a Class in Java

I want to get a Method of a Class in this Way:

int value = 5;
Class paramType = value.getClass();
String MethodName = "myMethod";
Class<?> theClass = obj.getClass();
Method m = theClass.getMethod(MethodName, paramType);

Is it possible to ignore MethodName case-sensitive? For example, if there is a method in theClass with name foo, how can I find it with having MethodName=fOO?

like image 767
HoseinPanahi Avatar asked May 27 '17 10:05

HoseinPanahi


1 Answers

Java is case sensitive, so there's no such built-in method. You could, however, implement it yourself by iterating over all the methods and checking their names and parameter types:

public List<Method> getMethodsIgnoreCase
    (Class<?> clazz, String methodName, Class<?> paramType) {

    return Arrays.stream(clazz.getMethods())
                 .filter(m -> m.getName().equalsIgnoreCase(methodName))
                 .filter(m -> m.getParameterTypes().length ==  1)
                 .filter(m -> m.getParameterTypes()[0].equals(paramType))
                 .collect(Collectors.toList());
}

Note: This method looks for a method with a single argument that matches the given type, to match the requirement in the OP. It can easily be generalized to receive a list/array of argument types though.

like image 175
Mureinik Avatar answered Sep 25 '22 02:09

Mureinik