No Such Method Exception - using Reflection

2019-09-08 03:49发布

I'm trying to use reflection (on an android app) to invoke a method and it work only when I do it this way

Object impresora     = loadedClass.newInstance();
Object args[]        = {"00:15:0E:E0:DD:38", true};

for(Method m : impresora.getClass().getDeclaredMethods())
    if("BTConnection".compareTo(m.getName()) == 0)
         int resultado = (Integer) m.invoke(impresora, args);

But I don't want to iterate everytime, so I'm trying this way, but this is where I get the NoSuchMethodException

Method m = impresora.getClass().getDeclaredMethod("BTConnection");
m.invoke(impresora, args);

Thanks in advance

2条回答
做自己的国王
2楼-- · 2019-09-08 04:16

In your first snippet you're doing object.getClass() in your second snippet you're doing impresora.getClass().

查看更多
地球回转人心会变
3楼-- · 2019-09-08 04:36

You need the actual parameter types in order to find the methods otherwise it will try to look for the method without an argument which I am guessing doesn't exist in your class.

Seeing:

Object args[] = {"00:15:0E:E0:DD:38", true};

I am guessing that the first argument is a String and second one is a boolean, so in order to find the method you need to do the following:


Method m = c.getDeclaredMethod("BTConnection", String.class, Boolean.class);    
查看更多
登录 后发表回答