title: Java Generics puzzle - Get the class/type of object of generic type so that you can ensure the type later
body: <p>Look at this short class. </p>
  
  <p>What does it do? It is a HashMap where the key is a Class object and the value is a Hashmap with key and value of the type which is defined by the Class object.</p>
  
  <p>Say you want to have a method add(K obj), that will be a convenience method. Why would you force a user to type add(Person.class, personInstance), when you can also let him just pass you the instance itself - the code should be able to take the class of the object and put the instance under the key being the class of the object. But I can't. The add(K obj) convenience method does not compile: </p>
  
  <pre><code>public class TypedHashmap extends HashMap&lt;Class, HashMap&gt; {
  
      public &lt;K&gt; HashMap&lt;K, K&gt; getHashMap(Class&lt;K&gt; type) {
          return (HashMap&lt;K, K&gt;) getOrDefault(type, new HashMap&lt;K, K&gt;());
      }
  
      public &lt;K&gt; void add(K obj, Class&lt;K&gt; type) {
          HashMap&lt;K, K&gt; toModify = getHashMap(type);
          toModify.put(obj, obj);
      }
  
      public &lt;K&gt; void add(K obj) {
          add(obj, obj.getClass());
      }
  }
  </code></pre>
  
  <p>The compile error:</p>
  
  <p><img src="https://i.stack.imgur.com/bXxJL.png" alt="enter image description here"></p>
  
  <p>I can see that Java is not sure about obj.getClass() type. But I do not see why. Is it because it cannot ensure that the class is not actually something extending the K? What is the problem here? Can this be somehow worked around?</p>