繁体   English   中英

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

[英]call to method.invoke with variable number of arguments

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

    }

}

您可以使用以下代码段尝试一下。 这个想法是您将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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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