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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With