I’m trying to allow a user to call any method on a server using sockets and reflection. The client already knows the method names and the number of parameters, but not the actual parameter types.
Every method on the server takes 0 or more primitive arguments (including strings) and returns a primitive. I’m taking input from the user in the client using a Scanner, so everything is a string, and I’m using .split(” “) to separate the parameters.
How do I automatically parse these strings into their correct types (int, double, boolean, char, etc) on the server?
Here’s what I’m currently doing on the server.
clientOutput and clientInput are an ObjectOutputStream and ObjectInputStream on the socket, and m is the method I’m calling.
Class<?>[] parameterTypes = m.getParameterTypes();
clientOutput.writeObject(parameterTypes.length);
clientOutput.flush();
Object[] parameters = (Object[]) clientInput.readObject();
for (int i = 0; i < parameterTypes.length; i++) {
//Some sort of if statement? Some way to handle booleans or chars?
parameters[i] = NumberFormat.getInstance().parse((String) parameters[i]);
}
result = m.invoke(math, parameters);
And then I send the result (which is an object) back to the client, and it prints it out.
When you iterate through the parameter types, check for the class name and parse it accordingly.