0

I have Button and I can get any of its methods such as getText,setText ... using

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

but when I try to get "setOnClickListener" method using the same code Method mth = myButton.getClass().getMethod("setOnClickListener", parameterTypes); I am getting Exception : "NoSuchMethodException" Exception.

What I have tried:

send empty params

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

the function actually not found . its clearly that I have some misunderstanding here . may be its not posible to reach this method?? Thanks in advance.

the_farmer
  • 649
  • 1
  • 8
  • 23

2 Answers2

0

You should provide correct parameter types

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

You can always view parameter at class/method docs View.setOnClickListener

gio
  • 4,950
  • 3
  • 32
  • 46
0

I'm not sure what

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

is really what do you want. This condition will be true if the arrMethods[i].getName() returns the reference to the same object referred to by MethodName.

I think you would check if the strings are equal:

if(arrMethods[i].getName().equals(MethodName)
Vladimir
  • 1,532
  • 1
  • 13
  • 13
  • the function works when i write this myBtn.setOnClickListener(elemListener);so the function name is "setOnClickListener" like "setText","getText" ... so I wold like to know why my code not working if to this specific function there is different name or it cant be access in this way – the_farmer Mar 25 '12 at 08:53