I am currently working on a very simple client-server-connection. The client and the server are connected through sockets and communicate by using streams.
Now I want the client to be able to invoke methods on the server. Therefore the client should send a message to the server. This message is then split into two Strings. The first string methodName
contains the name of the method to be called. The second String objectName
contains the name of an object on which the method should be called.
One way to this would be by using if-statements like if(methodName.equals("mymethod")){mymethod()};
. This method works just fine and can be extended to check for objectName
as well. Still I am very unhappy with this solution. I want to be able to invoke a lot of different methods on a lot of different objects (even on objects that don't even exist yet). I just don't want to write thousand of if-statements or cases.
That's why I try to find a different approach. I already found a partial solution for methodName
by using this:
java.lang.reflect.Method method = myObject.getClass().getMethod(methodName);
method.invoke(myObject);
This would effectively turn the String value of methodName
into a reference to the corresponding method. That's just what I was looking for.
But it comes with the problem that both instructions require an object reference. By now the "name" of that reference is still stored in objectName
and most important, it is a String value and not a reference. What I am now looking for is a instruction like this:
Object myObject = turnTheStringValueIntoAReference(objectName);
For now we can just assume that there already exists an object reference with the name that is stored in objectName. Otherwise there might also be a way to do something like this:
Object turnTheStringValueIntoAReference(objectName) = new Object();
I tried my best to find a way to turn a String value into a object reference but sadly I couldn't find any solution. I now have reached to point where I was thinking that this "feature" purposely doesn't exist in Java because it would basically eliminate type safety. Not to mention all the exceptions that might occur.
However I still would be very happy and very thankful if anyone could tell me if there actually is a way to do this. Maybe I just didn't figure it out yet.
With further research I found out that RMI might be an alternative to this. I guess RMI would even be a much better way to this. The reason I still don't want to RMI is that I plan on expanding the server in a way that it doesn't only accept my own client but also clients that are written in different languages. I think managing this will be ways easier if the client only needs to send a message than somehow support Java RMI without being written in Java.
Well, I think that's it. I would really appreciate your help.