title: Java Map with variable generics as values
body: <p>So here's a slightly tricky question (for me).</p>
  
  <p>I have a generic object. Call it MyObject. This object has a method which returns something of the type T:</p>
  
  <pre><code>public class MyObject&lt;T&gt;
  {
      private T _t;
  
      public MyObject(T t)
      {
          _t = t;
      }
  
      //...
  
      public T get()
      {
          return _t;
      }
  }
  </code></pre>
  
  <p>(Obviously my "MyObject" does a bit more but that's the gist).</p>
  
  <p>Now, I want to have a map of this type:</p>
  
  <pre><code>Map&lt;String, MyObject&lt;?&gt;&gt; m = new HashMap&lt;&gt;();
  </code></pre>
  
  <p>I want to be able to fetch maps using some predefined string name, and these maps can be of any MyObject. For example, I could call:</p>
  
  <pre><code>m.put("map_1", new MyObject&lt;String&gt;("String"));
  m.put("map_2", new MyObject&lt;Integer&gt;(new Integer(3));
  m.put("map_3", new MyObject&lt;Long&gt;(new Long(5));
  </code></pre>
  
  <p>etc.</p>
  
  <p>But - and here's the tricky part - I want the map to "remember" the parameterized type of MyObject when I fetch some value from the map. Using</p>
  
  <pre><code>m.get("map_1");
  </code></pre>
  
  <p>would return a </p>
  
  <pre><code>MyObject&lt;Object&gt; 
  </code></pre>
  
  <p>type, since the map was defined as containing </p>
  
  <pre><code>MyObject&lt;?&gt; 
  </code></pre>
  
  <p>values. Thus:</p>
  
  <pre><code>m.get("map_1").get() // &lt;-- This is an Object, not a String! 
  </code></pre>
  
  <p>What modification (if any) is possible, in order to be able to get the correct - full - information regarding the MyObject fetched object, such that invoking the last line (m.get("map_1")) would return a </p>
  
  <pre><code>MyObject&lt;String&gt;
  </code></pre>
  
  <p>Thanks :)</p>
  
  <p>Amir. </p>