Thundercleez
Thundercleez

Reputation: 401

Java: NoSuchMethodException even though the method exists

So I have a class with 2 public methods defined. When I call getDeclaredMethods, then loop over the results, printing the names, both correctly show up. So not only does the method exist, but the reflection call finds it.

But when I try calling the method, like in the code below, I get a NoSuchMethodException. So why can't it find it when invoking?

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;
  }
}

Upvotes: 0

Views: 771

Answers (1)

0xh3xa
0xh3xa

Reputation: 4857

You should put the parameters' types of the method, your code should look like this:

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;
}

Upvotes: 5

Related Questions