所以我有一个定义了 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/