Ignore case-sensitive "methodName" to get class method in Java

I want to get the class method as follows:

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

Can I ignore MethodNamecase sensitive? For example, if there is a method in theClasswith a name foo, how can I find it with MethodName=fOO?

+4
source share
1 answer

Java is case sensitive, so there is no such built-in method. However, you can implement it yourself, iterate over all methods and check 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());
}

: , , OP. / .

+4

Source: https://habr.com/ru/post/1678026/


All Articles