【问题标题】:Android cant reach "setOnClickListener" method by using getMethod ,getMethods,getDeclaredMethodAndroid 无法使用 getMethod、getMethods、getDeclaredMethod 达到“setOnClickListener”方法
【发布时间】:2012-04-06 08:21:58
【问题描述】:

我有 Button,我可以使用它的任何方法,例如 getText、setText ...

Method mth = myButton.getClass().getMethod("getText", parameterTypes);

但是当我尝试使用相同的代码获取“setOnClickListener”方法时 Method mth = myButton.getClass().getMethod("setOnClickListener", parameterTypes); 我收到异常:“NoSuchMethodException”异常。

我尝试过的:

发送空参数

Class<?>[] parameterTypes = new Class[] {};
`Method mth = myButton.getClass().getMethod("setOnClickListener", parameterTypes);` NOT working the same Exception:  "NoSuchMethodException"

i tried to get all the methods and identify it by name.
Method[] arrMethods = objElem.getClass().getMethods();

Method listener = getMethodByName(arrMethods,"setOnClickListener");

public Method getMethodByName(Method[] arrMethods,String MethodName)
    {
        for(int i=0;i<arrMethods.length;i++)
        {
            if(arrMethods[i].getName() == MethodName)
            {
                return arrMethods[i];
            }
        }
        return null;
    }

函数实际上没有找到。 很明显我在这里有一些误解。 可能无法达到这种方法? 提前致谢。

【问题讨论】:

    标签: android reflection getmethod


    【解决方案1】:

    我不确定是什么

    if(arrMethods[i].getName() == MethodName)
    

    真的是你想要的。如果 arrMethods[i].getName() 返回对 MethodName 引用的相同对象的引用,则此条件为真。

    我想你会检查 strings 是否相等:

    if(arrMethods[i].getName().equals(MethodName)
    

    【讨论】:

    • 这个函数在我写这个 myBtn.setOnClickListener(elemListener) 时起作用;所以函数名是 "setOnClickListener" 就像 "setText","getText" ...所以我想知道为什么我的代码如果此特定功能有不同的名称或无法以这种方式访问​​,则无法正常工作
    【解决方案2】:

    您应该提供正确的参数类型

    Class<?>[] parameterTypes = new Class[] {View.OnClickListener.class};
    

    您始终可以在类/方法文档View.setOnClickListener中查看参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2014-11-06
      相关资源
      最近更新 更多