Reputation: 8484
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
);
}
}
Upvotes: 0
Views: 2465
Reputation: 8095
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;
}
Upvotes: 1