title: Set value for object field by reflection in java
body: <p>First, I have an object like that:</p>
  
  <pre><code>public class Entity {
      public int data1;
      public String data2;
      public float data3;
      public SubEntity data4;
  }
  
  public class SubEntity{
      public int id;
      public SubEntity(int id){
        tis.id = id;
      }
  }
  </code></pre>
  
  <p>And a HashMap:</p>
  
  <pre><code>  HashMap&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
    map.put("data1", 1);
    map.put("data2", "name");
    map.put("data3", 1.7);
    map.put("data4", new SubEntity(11));
  </code></pre>
  
  <p>I need the right way to set value for all field of entity dynamic by use reflect from hashmap. Something like this:</p>
  
  <pre><code>    for (Field f : entity.getClass().getDeclaredFields()) {
         String name = f.getName();
         Object obj = map.get("name");
         // Need set value field base on its name and type. 
  
  } 
  </code></pre>
  
  <p>How can I achieve that? Assume I have many sub classes in entity.</p>