Search code examples
javareflectionrmirpc

Execute a String as method?


Is it possible to execute a String as method?

Let's say I have a server and a client. The client is send a "sayHello()" string. Could the client just execute this string as method on client side, if he has a private void sayHello() method?

I know I could call the method by comparing the string to certain values and call functions based on this. But I'm exactly looking into something like described above.


Solution

  • Reflection isn't very hard to code:

    public void invokeByName(String methName) {
      try { getClass().getDeclaredMethod(methName).invoke(this); } 
      catch (RuntimeException e) { throw e; }
      catch (Exception e) { throw new RuntimeException(e); }
    }