Java:NoSuchMethodException,即使该方法存在

Thu*_*eez 0 java reflection

所以我有一个定义了 2 个公共方法的类。当我调用 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

Ahm*_* M. 5

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

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;
}
Run Code Online (Sandbox Code Playgroud)