java - 为什么 getmethod 返回 null 即使该方法存在

标签 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);
}
catch(Exception e)
{

}
System.out.println(classMethod == null);

第一个 print 打印 true,但第二个也打印 true

为什么会这样?

最佳答案

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

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

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

  • Class.getMethod(name, parameters) 仅返回公共(public)方法,也许您想对 protected 、默认的或私有(private)的方法使用 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}));

关于java - 为什么 getmethod 返回 null 即使该方法存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997478/

相关文章:

c++ - 作为类成员的常量引用

c# - 获取 Enumerable.First() 的 MethodInfo 与 Enumerable.OfType() 的 MethodInfo?

C# 等价于 Java 的 continue <label>?

java - 使用 HtmlUnit 时,如何配置底层 NekoHtml 解析器?

java - 运行时类型识别

c++ - 在 C++ 中,如何确保一个对象在另一个对象之前构造?

java - 是否可以为相同的 xs :simpleContent elements? 创建单个类映射

php - Laravel:绑定(bind)到 IoC 容器

c# - 从事件处理程序确定发件人对象

swift - 如何反射(reflect) NSManagedObject 的非托管属性