简体   繁体   中英

call to method.invoke with variable number of arguments

Having

public Object callRemote (String sRemoteInterface, String sMethod,
            Object... arguments);

I want to do something like:

method.invoke(
            instance, 
            arguments..., 
            sessionId
        );

So it works for methods with a variable number of arguments.

How can I do it?

[EDIT] Here is the actual code I am using right now. It works for 1 or 2 arguments, but it needs to be made generic for N arguments:

public Object callRemote (String sRemoteInterface, String sMethod,
            Object... arguments) throws Exception {

    Object instance;
    Method method;

    if (sRemoteInterface==null) {

        throw new Exception("Must specify a remote interface to locate.");

    }

    instance = this.locator.getRemoteReference(sRemoteInterface, this.sessionId);

    if (arguments.length == 2) {

        method = instance.getClass().getMethod(
            sMethod, 
            arguments[0].getClass(),
            arguments[1].getClass(),
            int.class
        );

        return method.invoke(
            instance, 
            arguments[0], 
            arguments[1], 
            sessionId
        );

    } else {

        method = instance.getClass().getMethod(
            sMethod, 
            arguments[0].getClass(), 
            int.class
        );

        return method.invoke(
            instance, 
            arguments[0], 
            sessionId
        );

    }

}

You could try it with following snippet. The idea is that you pass the varargs through (getMethod also has varargs). I omitted the code for instance creation.

int sessionId;

Object callRemote(Object instance, String sMethod, Object... arguments) throws Exception {
    Class<?>[] argumentTypes = createArgumentTypes(arguments);
    Method method = instance.getClass().getMethod(sMethod, argumentTypes );
    Object[] argumentsWithSession = createArguments(arguments);
    return method.invoke(instance, argumentsWithSession);
}

Object[] createArguments(Object[] arguments) {
    Object[] args = new Object[arguments.length + 1];
    System.arraycopy(arguments, 0, args, 0, arguments.length);
    args[arguments.length] = sessionId;
    return args;
}

Class<?>[] createArgumentTypes(Object[] arguments) {
    Class[] types = new Class[arguments.length + 1];
    for (int i = 0; i < arguments.length; i++) {
        types[i] = arguments[i].getClass();
    }
    types[arguments.length] = int.class;
    return types;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM