Java 反射获取单个 float 参数的方法名
可以通过以下代码使用反射获取到只有一个 float 参数的方法名:
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) {
Class<?> clazz = MyClass.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == float.class) {
System.out.println(method.getName());
}
}
}
}
class MyClass {
public void method1(float value) {
// ...
}
public void method2(int value) {
// ...
}
public void method3(float value) {
// ...
}
}
在上述代码中,首先通过clazz.getDeclaredMethods()获取到类MyClass中的所有方法。然后使用method.getParameterCount()获取方法的参数个数,若参数个数为1,则使用method.getParameterTypes()[0]获取参数类型,与float.class进行比较,如果相等,则输出该方法的名称。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/olRY 著作权归作者所有。请勿转载和采集!