title: Java dynamically create object array of instance variables
body: <p>I have several pojos whose instance variables need to be converted to Object arrays.  I am trying to find a way that this can be handled dynamically instead of adding a toObjectArray() method in each pojo.</p>
  
  <p>Here is a sample class with the toObjectArray() method that I would like to get rid of:</p>
  
  <pre><code>public class Contact {
  
    private String lastName;
    private String firstName;
  
    public String getLastName() {
      return lastName;
    }
  
    public void setLastName(String lastName) {
      this.lastName = lastName;
    }
  
    public String getFirstName() {
      return firstName;
    }
  
    public void setFirstName(String firstName) {
      this.firstName = firstName;
    }
  
    public Object[] toObjectArray() {
      return new Object[] {
        this.getLastName(),
        this.getFirstName(),
      };
    }
  
  }
  </code></pre>
  
  <p>The instance variables do not have to be returned in order.  I have a custom annotation which allows me to reflect proper order for the object array.  I'm simply wondering if it is possible to dynamically iterate the instance variables and values of an object in order to create an object array.</p>
  
  <p>Something like this...</p>
  
  <pre><code>public static Object[] toObjectArray(Object obj) {
    /// cast Object to ?
    /// iterate instance variables of Contact
    /// create and return Object[]
  }
  
  public static void main(String[] args) {
    Contact contact = new Contact();
    contact.setLastName("Garcia");
    contact.setFirstName("Jerry");
  
    Object[] obj = toObjectArray(contact);
  }
  </code></pre>
  
  <p>Any help would be greatly appreciated.  Please let me know if I need to be more clear.</p>
  
  <p>Thank you!</p>