java - Trying to call a method using reflection and automatically parsing input -
java - Trying to call a method using reflection and automatically parsing input -
i'm trying allow user phone call method on server using sockets , reflection. client knows method names , number of parameters, not actual parameter types.
every method on server takes 0 or more primitive arguments (including strings) , returns primitive. i'm taking input user in client using scanner, string, , i'm using .split(" ") separate parameters.
how automatically parse these strings right types (int, double, boolean, char, etc) on server?
here's i'm doing on server. clientoutput , clientinput objectoutputstream , objectinputstream on socket, , m method i'm calling.
class<?>[] parametertypes = m.getparametertypes(); clientoutput.writeobject(parametertypes.length); clientoutput.flush(); object[] parameters = (object[]) clientinput.readobject(); (int = 0; < parametertypes.length; i++) { //some sort of if statement? way handle booleans or chars? parameters[i] = numberformat.getinstance().parse((string) parameters[i]); } result = m.invoke(math, parameters);
and send result (which object) client, , prints out.
when iterate through parameter types, check class name , parse accordingly.
( class<?> c : paramtypes ) if ( "int".equals(c.getsimplename() ) { // parse int } else if ("boolean".equals(c.getsimplename() ) { // parse boolean } }
java reflection
Comments
Post a Comment