我希望以这种方式得到一个类的方法:
int value = 5;
Class paramType = value.getClass();
String MethodName = "myMethod";
Class> theClass = obj.getClass();
Method m = theClass.getMethod(MethodName, paramType);
是否可以忽略MethodName区分大小写?
例如,如果theClass中有一个名为foo的方法,我该怎么办
找到它有MethodName = fOO?
解决方法:
Java区分大小写,因此没有这样的内置方法.但是,您可以通过迭代所有方法并检查其名称和参数类型来自行实现它:
public List 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中的要求.它可以很容易地推广到接收参数类型的列表/数组.
标签:java,reflection
来源: https://codeday.me/bug/20190622/1265057.html