使用可变数量的参数调用method.invoke

时间:2015-03-03 09:55:49

标签: java reflection variadic-functions

具有

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

我想做类似的事情:

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

因此它适用于具有可变数量参数的方法。

我该怎么做?

[编辑]这是我现在使用的实际代码。它适用于1或2个参数,但需要为N个参数设置通用:

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

    }

}

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码段进行尝试。这个想法是你通过varargs(getMethod也有varargs)。我省略了实例创建的代码。

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