title: Java method returning HashMap<key, Object> with dynamic object
body: <p>I have several TSV files and want to read them and populate in a HashMap of </p>
  
  <blockquote>
    <p>[first field --> other fields in an object].</p>
  </blockquote>
  
  <p>For simplicity, assume that there are two files:</p>
  
  <blockquote>
    <p>File 1 contains two fields (field1 and field2).<br>
    File 2 contains three fields (f1, f2 and f3).</p>
  </blockquote>
  
  <p>So I defined two classes whose objects are to be values in the hashMap:</p>
  
  <pre><code>Class1{
      String field1 = "";
      String field2 = "";
  }
  Class2{
      String f1 = "";
      String f2 = "";
      String f3 = "";
  }
  </code></pre>
  
  <p>Now, I have these methods:</p>
  
  <pre><code>public static HashMap&lt;String, Class1&gt; readTSV1(String fileName, Class1 c){
  ...
  }
  
  public static HashMap&lt;String, Class2&gt; readTSV2(String fileName, Class2 c){
  ...
  }
  ...
  </code></pre>
  
  <p>But I don't want to define various methods for reading from different files:</p>
  
  <p>I want something like this:</p>
  
  <pre><code>public static HashMap&lt;String, Object&gt; readTSV(String fileName, Class&lt;?&gt; c){
      HashMap&lt;String, c.getClass()&gt; hm = new HashMap&lt;String, c.getClass()&gt;(); //error.
      //Look which field names are in type c, 
      //and then read two or three fields from file, 
      //and put them as key and values of hm (first field is key, other fields are put in instance of the respective class, and put as values)
      return hm;
  }
  
  static void main(String[] args){
      Class1 c1;
      HashMap&lt;String, Class1&gt; hm1 = new HashMap&lt;String, Class1&gt;();
      hm1 = readTSV("firstFile.tsv", c1.getClass())
  
      Class2 c2;
      HashMap&lt;String, Class2&gt; hm1 = new HashMap&lt;String, Class2&gt;();
      hm1 = readTSV("firstFile.tsv", c2.getClass())
  
      ...
  }
  </code></pre>
  
  <p>Any ideas? ...</p>