No Such Method Exception - using Reflection

2019-09-08 04:10发布

问题:

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

回答1:

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



回答2:

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