这样的方法异常 - 使用反射 [英] No Such Method Exception - using Reflection
问题描述
我想使用反射(在Android应用程序)调用一个方法,它只有当我做这样的工作。
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);
但我不想要遍历每次,所以我想这样,但是这就是我得到的NoSuchMethodException
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);
在此先感谢
推荐答案
您需要以其他方式找到方法的实际参数类型,它会尝试去寻找方法,没有它我猜在不存在的说法你的类。
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.
看到:
对象ARGS [] = {00:15:0E:E0:DD:38,真实};
我猜测,第一个参数是一个字符串和第二个是一个布尔值,所以为了找到方法,你需要做到以下几点:
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);
这篇关于这样的方法异常 - 使用反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!