title: Casting objects via reflection in Java
body: <p>I am writing a deserializer method, which looks like so:</p>
  
  <pre><code>public &lt;T&gt; T deserialize(Object[] result, String[] fields, Class&lt;T&gt; type);
  </code></pre>
  
  <p>So basically I will be passed in a result array of data which is all objects, and a class type T which I need to convert the data in the array to the types in the given class, and create a new class of type T and return it. The <code>String[]</code> fields is the field names corresponding to the data in <code>Object[]</code> result. The field names will correspond to the Class <code>T</code>.</p>
  
  <p>The casting will need to use reflection of the given class to find out the type of each field.</p>
  
  <p>eg.</p>
  
  <pre><code>result = ["Mike", "London", 28];
  fields = ["name", "location", "age" ];
  </code></pre>
  
  <p>Class T = </p>
  
  <pre><code>public class GivenClass{
  
    private String name;
    private String location;
    private Integer age;
  
    public GivenClass(String name, String location, Integer age){
      this.name = name;
      this.location = location;
      this.age = age;
    }
  }
  </code></pre>