Java 为什么getmethod即使存在也返回null
我有以下代码:Java 为什么getmethod即使存在也返回null,java,class,reflection,methods,Java,Class,Reflection,Methods,我有以下代码: String methodName = "main"; Method[] methods = classHandle.getMethods(); for (Method m : methods) { System.out.println(m.getName().equals(methodName); } Method classMethod = null; try { classMethod = classHandle.getMethod(methodName);
String methodName = "main";
Method[] methods = classHandle.getMethods();
for (Method m : methods)
{
System.out.println(m.getName().equals(methodName);
}
Method classMethod = null;
try
{
classMethod = classHandle.getMethod(methodName);
}
catch(Exception e)
{
}
System.out.println(classMethod == null);
第一次打印的是true
,但第二次打印的也是true
为什么会发生这种情况?要获得静态void main(字符串[]args),请使用以下命令
classHandle.getDeclaredMethod("main", String[].class);
可能的原因(写在我们知道我们是在静态void main之后)
- getMethod(名称,参数)只返回公共方法,也许您想对受保护的、默认的或私有的方法使用getDeclaredMethod(名称,参数)
- 参数不匹配。“main”是否接受任何参数?传递给getDeclaredMethod()或getMethod()的参数必须完全匹配
private class Horse {
protected void makeNoise(int level) {
}
}
// OK
System.out.println(Horse.class.getDeclaredMethod("makeNoise", new Class<?>[]{int.class}));
// throws NoSuchMethodException - parameters don't match
System.out.println(Horse.class.getDeclaredMethod("makeNoise"));
// throws NoSuchMethodException, not a public method
System.out.println(Horse.class.getMethod("makeNoise", new Class<?>[]{int.class}));
私人级马{
受保护的void makeNoise(整数级){
}
}
//嗯
System.out.println(Horse.class.getDeclaredMethod(“makeNoise”,新类[]{int.class}));
//抛出NoSuchMethodException-参数不匹配
System.out.println(Horse.class.getDeclaredMethod(“makeNoise”);
//抛出NoSuchMethodException,而不是公共方法
System.out.println(Horse.class.getMethod(“makeNoise”,新类[]{int.class}));
我假设“classHandle”是类的一种类型
第一个循环只检查方法名,不关心方法参数
“public Method getMethod(String name,Class…parameterTypes)”的完整签名告诉我们,您实际上正在尝试查找名为“methodName”的0参数方法
是否确实存在具有此名称和0个参数的方法?,因为该方法的参数不匹配。您需要在对getMethod()的调用中指定参数类型。返回所有
方法的数组,您只需检查名称。对于main
,它将返回true;但是对于从对象继承的所有方法,它将返回false
当您仅以方法名称作为参数调用时,您要求的是不带参数的方法
但是main
接受一个参数,一个String[]
,因此getMethod
抛出一个NoSuchMethodException
。你抓住了它,但什么也没做。(您正在“吞咽”异常,这通常是一个坏主意。)因此,classMethod
保持null
并输出true
要查找main
,请将参数的类型作为附加参数传递:
Method classMethod = classHandle.getMethod(methodName, String[].class);
当方法不存在时调用classHandle.getMethod
(假设classHandle
是一个Class
)应该导致抛出NoSuchMethodException
,而不是返回null
。不,实际上我正在搜索一个类的主函数,该函数获取字符串[]args.as在“公共静态void main(字符串[]args)”中?然后,您的“getMethod('main',…)”调用中缺少参数类型规范。在这种情况下,您需要执行classHandle.getMethod(methodName,String[].class)代码>@R4J是的,但在JavaDoc上写着,当不指定任何参数时,它就像一个空数组。@JohnDoe,请告诉我们您的“main”方法是如何声明的。