title: Java generics - map of formatters
body: <p>A <code>Formatter&lt;T&gt;</code> knows how to format <code>T</code> to string:</p>
  
  <pre><code>public interface Formatter&lt;T&gt; {
    String format(final T t);
  }
  </code></pre>
  
  <p>I would like to have a <code>Map</code> of formatters, one for <code>Integer</code>, one for <code>Date</code> etc:</p>
  
  <pre><code>Map&lt;Class, Formatter&gt; formatters;
  </code></pre>
  
  <p>The intended use would be:</p>
  
  <pre><code>formatters.put(Integer.class, new Formatter&lt;Integer&gt;() {
      public String format(Integer i) {
        return i.toString;
      }
  });
  </code></pre>
  
  <p>Is there some way to enforce that the key-values will agree on the <code>Class</code> type? That if I say <code>put(Integer.class, new Formatter&lt;Integer&gt;(){...})</code> it will work but <code>put(Integer.class, new Formatter&lt;Date&gt;(){...})</code> will not?</p>
  
  <p>What I am trying now is to use ? as the type:</p>
  
  <pre><code>Map&lt;Class&lt;?&gt;, Formatter&lt;?&gt;&gt; formatters;
  </code></pre>
  
  <p>But then I cannot use formatters inside this map:</p>
  
  <pre><code>Object obj = Integer.valueOf(15);
  formatters.get(obj.getClass()).format(obj);
  Error: The method format(capture#3-of ?) in the type Formatter&lt;capture#3-of ?&gt; is not applicable for the arguments (Object)
  </code></pre>
  
  <p>Any clarification would be welcome.</p>