2013-06-24 109 views
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); 
} 

任何幫助將不勝感激。如果我需要更清楚,請讓我知道。

謝謝!

+1

也許反射? – 2013-06-24 02:35:29

回答

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; 
} 
+0

+1你的答案比我的答案更完整 – fmodos

+0

這是完美的,謝謝!我不知道這個實例可以像這樣返回......非常有用。再次感謝。 – mmamane

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