Java:NoSuchMethodException,即使该方法存在

标签 java reflection

所以我有一个定义了 2 个公共(public)方法的类。当我调用 getDeclaredMethods 时,然后循环结果,打印名称,两者都正确显示。所以不仅该方法存在,而且反射调用也找到了它。

但是当我尝试调用该方法时(如下面的代码所示),我收到 NoSuchMethodException。那为什么调用的时候找不到呢?

public class Foo
{
  public byte[] read_status(Object arg)
  {
    byte[] test = new byte[10];
    for(int i = 0; i < 10; i++)
    {
      test[i] = (byte)i;
    }
    return test;
  }

  public int test(String s) throws Exception
  {
    Object r = this.getClass().getDeclaredMethod("read_status").invoke(this, (Object)s);
    byte[] bytes = (bytes[])r;
    for(int i = 0; i < bytes.length; i++)
    {
      System.out.println(""+bytes[i]);
    }
    return 0;
  }
}

最佳答案

您应该放置方法的参数类型,您的代码应如下所示:

public int test(String s) throws Exception {
    Object r = this.getClass().getDeclaredMethod("read_status", Object.class).invoke(this, (Object)s);
    byte[] bytes = (byte[])r;
    for(int i = 0; i < bytes.length; i++) {
      System.out.println(""+bytes[i]);
    }
    return 0;
}

关于Java:NoSuchMethodException,即使该方法存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60838700/

相关文章:

java - 我可以在 Java 中的 ArrayList<T> 实例上使用类字段吗?

java - 注释不可见?

java - 按内容等于文本的类查找元素

java - 如何用 Java 编写 Hello World 应用程序?

Java 射弹角度

.net - 如何获取.NET中对象的全名?

c# - 在 silverlight 中使用反射调用 routedevents 上注册的事件处理程序

java - 仅当对象具有特定注释时才通过反射调用 setText()

java - hibernate 中返回日期错误

java - 计算几何 : find where the triangle is after rotation, 在镜子上的平移或反射