1

我有几个 pojo,它们的实例变量需要转换为对象数组。我试图找到一种可以动态处理的方法,而不是在每个 pojo 中添加一个 toObjectArray() 方法。

这是一个带有 toObjectArray() 方法的示例类,我想摆脱它:

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(),
    };
  }

}

实例变量不必按顺序返回。我有一个自定义注释,它允许我反映对象数组的正确顺序。我只是想知道是否可以动态迭代对象的实例变量和值以创建对象数组。

像这样的东西...

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);
}

任何帮助将不胜感激。如果我需要更清楚,请告诉我。

谢谢!

4

2 回答 2

2

一种可能的方法是使用反射。

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;
}
于 2013-06-24T02:42:19.163 回答
0
//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);
}
}
于 2014-07-23T06:22:50.820 回答