title: How do I pass a method or object from client to server in Java?
body: <p>I have multiple clients and one server. Each client has a few commands at their disposal, eg:</p>
  
  <pre><code>public interface Command {
      public int run();
  }
  
  public class CommandOne implements Command {
      // ...
  }
  
  public class CommandTwo implements Command {
      // ...
  }
  </code></pre>
  
  <p>These commands can be executed within the client (on their machine) - or they can be "passed" to the server to be executed, and then a result will be returned.</p>
  
  <p>What is the simplest way of implementing both the client and server within Java?</p>
  
  <p>The following are what I've come up with:</p>
  
  <ul>
  <li>Serialize the command, pass it to the server, have the server deserialize it, run the command and return the result. (This won't work because methods cannot be serialized.)</li>
  <li>Pass a the command's name (as a String) to the server, have the server run a <code>switch</code> statement, instantiate a new command of the same type, run it, and return the result. This means if I ever add a new command class, I will have to update both the client and the server.</li>
  <li>Serialize the necessary method logic into some structure (JSON, XML, etc.), pass it to the server, have the server deserialize it into a custom class, run the method logic, and then return the result. This seems like overkill and requires writing a DSL.</li>
  </ul>
  
  <p>Is there something I'm missing?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Each request must be threaded in some way - because multiple clients could communicate with the server at the same time. This is probably not an issue with the above problem, though.</p>