title: Java generics: capture cannot be applied to Object
body: <p>I have code that has a <code>Map</code> of (Message)Handlers. I'm trying to make the handlers generified (as seen by the interface Handler). Without generics the handlers all need to cast from Object to the respective class, which would be nice to avoid (but everything works). For each message class (<code>Foo</code> below) I have a handler class.</p>
  
  <p>How can I keep a Map of any kind of Class to any kind of Handlers and get/call with "just" an <code>Object</code>? (the parameter to <code>handleMessage(Object)</code> can't be restricted)</p>
  
  <p>See MWE below.</p>
  
  <pre><code>import java.util.*;
  public class Logic
  {   
      Map&lt;Class&lt;?&gt;, Handler&lt;?&gt;&gt; handlers = new HashMap&lt;Class&lt;?&gt;, Handler&lt;?&gt;&gt;();
  
      public void run()
      {   
          handlers.put(Foo.class, new FooHandler());
      }   
  
      public void handleMessage(Object msg)
      {   
          Handler&lt;?&gt; handler = handlers.get(msg.getClass());
          if (handler != null) {
              handler.execute(msg);
          }   
      }   
  
      private interface Handler&lt;T&gt;
      {   
          public void execute(T msg);
      }   
  
      private class FooHandler implements Handler&lt;Foo&gt;
      {   
          public void execute(Foo msg) {}
      }   
  
      private class Foo {}
  }
  </code></pre>
  
  <p>This code produces:</p>
  
  <blockquote>
    <p>Logic.java:16: execute(capture#x of ?) in Logic.Handler cannot be applied > to (java.lang.Object)
                handler.execute(msg);</p>
  </blockquote>
  
  <p>How can this be repaired to work while still keeping the Handler interface generic?</p>