为什么即使方法存在,getmethod returns null

Why getmethod returns null even though the method exists

我有以下代码:

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.

为什么会这样?

要获取 static void main(String [] args) 使用以下内容

classHandle.getDeclaredMethod("main", String[].class);

可能的原因(写在我们知道我们在 static void main 之后)

  • Class.getMethod(name, parameters) returns 仅 public 方法,也许您想对受保护的默认方法或私有方法使用 getDeclaredMethod(name, parameters)
  • 参数不匹配。 "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}));

我假设 'classHandle' 是 Class 的一种?

您的第一个循环只检查方法名称而不关心方法参数。

'public Method getMethod(String name, Class... parameterTypes)' 的完整签名告诉我们您实际上是在尝试查找名称为 'methodName' 的 0 参数方法。

您确定具有这样的名称和 0 个参数的方法存在吗?

因为方法的参数不匹配。您需要在调用 getMethod() 时指定参数类型。

getMethods method return 是所有 Method 的数组,您只检查名称。对于 main,它将 return 为真,但是对于从 Object.

继承的所有方法,它将 false

当您仅使用方法名称作为参数调用 getMethod method 时,您要求的是不带参数的 Method

但是main接受一个参数,一个String[],所以getMethod抛出一个NoSuchMethodException。你正在抓住它,但什么都不做。 (你是 "swallowing" 例外,通常是个坏主意。)所以,classMethod 仍然是 null 并且输出 true

要查找 main,将参数的类型作为附加参数传递:

Method classMethod = classHandle.getMethod(methodName, String[].class);