我有几个pojos,其实例变量需要转换为Object数组。我试图找到一种方法,可以动态处理,而不是在每个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);
}
非常感谢任何帮助。如果我需要更清楚,请告诉我。
谢谢!
答案 0 :(得分: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;
}
答案 1 :(得分: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);
}
}