title: Java: Using Classes as a value in hashmap
body: <p>I'm trying to use custom Class as a value in a <code>Map&lt;String, Class&lt;?&gt;&gt;</code>. Following are relevant parts of code:</p>
  
  <p>Following is declaration and initialization of Map in <code>main()</code>:</p>
  
  <pre><code>public static Map&lt;String, Class&lt;?&gt;&gt; mapQuery2ResponseType = new HashMap&lt;String, Class&lt;?&gt;&gt;();
  static {
      mapQuery2ResponseType.put("string1", CustomClass1.class);
      mapQuery2ResponseType.put("string2", CustomClass2.class);
      mapQuery2ResponseType.put("string3", CustomClass3.class);
  }
  </code></pre>
  
  <p>Now I'm using this map to typecast an object to one of these classes: (assume that all classes contain a method <code>getName()</code> which return a <code>String</code>)</p>
  
  <pre><code>String name = (
                    (
                         mapQuery2ResponseType.get("string1")
                    )obj1
                ).getName();
  </code></pre>
  
  <p>where, <code>obj1</code> is of generic type <code>T</code>,</p>
  
  <p>but it's not allowing me to do so and says: <code>Syntax error on token "obj1", delete this token</code>.</p>
  
  <p>Please help me to understand where am I doing wrong?</p>
  
  <p><code>Edit:</code></p>
  
  <p>When I use following code, it worked perfectly giving me the expected result,</p>
  
  <pre><code>String name = (
                    (
                         CustomClass1
                    )obj1
                ).getName();
  </code></pre>
  
  <p>and <code>obj1</code> <strong>is of the same type</strong> as returned by <code>mapQuery2ResponseType.put("string1", CustomClass1.class);</code>.</p>
  
  <p>Here I can see 1 thing... if I use use it directly, i use it as <code>"CustomClass1"</code>, whereas if I get it from map by <code>mapQuery2ResponseType.get("string1")</code>, it returns <code>"CustomClass1.class"</code>. I'm not sure if there is any difference in these two approaches? If there is, what is it?</p>
  
  <p>So actually there wont be any conversion, it's just that I'm using it for <strong>large number of classes</strong>, and so trying to use a generalized approach.</p>
  
  <p><code>Edit2:</code></p>
  
  <p>as given in this question: <a href="https://stackoverflow.com/questions/15583978/java-difference-between-customclass1-and-customclass1-class?noredirect=1#comment22094692_15583978">Java: difference between “CustomClass1” and “CustomClass1.class”?</a>, I think, reflection is the only solution for this task. But can anybody explain how to do it using reflection?</p>