Shreyans jain
Shreyans jain

Reputation: 569

Java Reflection - Wrong number of arguments; expected 0, got 1

I am running this java code

ConnectivityManager connectivityManager = ((ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE));
    try {
        Method method = connectivityManager.getClass().getDeclaredMethod("getTetherableIfaces");
        String[] strings = ((String[]) method.invoke(connectivityManager));
        Log.i("hotspot", "getIface: "+strings.toString());
        Method methodTether = connectivityManager.getClass().getDeclaredMethod("tether",String.class);
        methodTether.setAccessible(true);
        String[] param =new String[]{"wlan0"};

        int i = (int) method.invoke(connectivityManager,"wlan0");
        Log.i(TAG, "getIface: "+ "errorcode"+ i);

    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

but i get this error

 java.lang.IllegalArgumentException: Wrong number of arguments; expected 0, got 1
    at java.lang.reflect.Method.invoke(Native Method)

And this is the tether function which i am trying to invoke.

 public int tether(String iface) {
    try {
        return mService.tether(iface);
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}

I tried to invoke the method with object[]{"wlan0"}, String[]{"wlan0"}, (object){"wlan0"}, {"wlan0"} and (Object[])String[]{"wlan0"} but I get the same error. I am not able to understand what am I doing wrong. For Any help I would be thankful.

Upvotes: 3

Views: 8492

Answers (2)

GBlodgett
GBlodgett

Reputation: 12819

In the line

Method method = connectivityManager.getClass().getDeclaredMethod("getTetherableIfaces");

method.invoke() will now call getTetherableIfaces() as invoke():

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters

which looks like a getter method and would thus accept no parameters. Then you try to pass an argument which will cause this error

String[] strings = ((String[]) method.invoke(connectivityManager));

It looks like you meant to call methodTether.invoke()

Upvotes: 2

ᴇʟᴇvᴀтᴇ
ᴇʟᴇvᴀтᴇ

Reputation: 12751

The error says "Wrong number of arguments; expected 0, got 1". That means the method you are calling is not the one you think it is. The method being called does not have any arguments and you are passing an argument to it.

You are invoking method instead of methodTether.

Upvotes: 3

Related Questions