Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
1  
Maybe reflection? –  user1181445 Jun 24 '13 at 2:35

2 Answers 2

up vote 2 down vote accepted

One possible way could be using reflection.

static <T> Object[] getFieldValues(final Class<T> type, final T instance) {

    final Field[] fields = type.getDeclaredFields(); // includes private fields

    final Object[] values = new Object[fields.length];

    for (int i = 0; i < fields.length; i++) {
        if (!fields[i].isAccessible()) {
            fields[i].setAccessible(true); // enables private field accessing.
        }
        try {
            values[i] = fields[i].get(instance);
        } catch (IllegalAccessException iae) {
            // @@?
        }
    }

    return values;
}
share|improve this answer
    
+1 your answer is more complete than mine –  fmodos Jun 24 '13 at 2:50
    
This is perfect, thank you! I didn't know the instance could be cast in the return like that... very useful. Thanks again. –  user2514739 Jun 24 '13 at 14:45
//Creating dyanamic class object[dynamic array] size for Object.

//Defining Testclass  for creatring menu buttons




public class TestClass extends AbstractAction{
        boolean literal;
        public TestClass(String literal) {
            super(literal);
        }
        public void actionPerformed(ActionEvent e) {

        }
    }


   ArrayList<TestClass> ObjectArray= new ArrayList<TestClass>();


   //Here ObjectArray is defined as dynamic array class object.

   //Insert new Class objects to the ObjectArray

ObjectArray.add( new TestClass("Button1")) ;
ObjectArray.add( new TestClass("Button2")) ;
ObjectArray.add( new TestClass("Button3")) ;

//Converting ArrayList object to  ClassObject array

TestClass testclassObject[]=ObjectArray.toArray(new [ObjectArray.size()])


//Using of Class object array


for (TestClass  subAction : testclassObject) {

  if(subAction != null){
        JButton  subButton = new JButton ((String)subAction.getValue(Action.NAME), null);
        subButton.addActionListener(subAction);

//Adding buttons to JPanel

        JPanel buttonpanel= new JPanel();                   
         buttonpanel.add(subButton);
}
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.