gpt4 book ai didi

java - 忽略大小写敏感 "methodName"获取 Java 类的方法

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:28 29 4
gpt4 key购买 nike

我想通过这种方式获取一个类的方法:

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<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 中的要求。不过,它可以很容易地概括为接收参数类型的列表/数组。

关于java - 忽略大小写敏感 "methodName"获取 Java 类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44215797/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com