6

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?

HoseinPanahi
  • 582
  • 2
  • 8
  • 18
  • 1
    No, Java is case sensitive so it is possible to have two separate methods like `foo(String s)` and `Foo(String s)` in the same class. You need to provide your own implementation and handle this case. – Pshemo May 27 '17 at 10:39
  • [Get all methods and check them yourself, like for fields](https://stackoverflow.com/questions/5351108/java-reflection-ignore-case-when-using-getdeclaredfield). There is no onboard `getMethodsCaseInsensitive` feature. – Tom May 27 '17 at 10:39

1 Answers1

7

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350