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.
Here is a sample class with the toObjectArray() method that I would like to get rid of:
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(),
};
}
}
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.
Something like this...
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);
}
Any help would be greatly appreciated. Please let me know if I need to be more clear.
Thank you!