2013-08-04 58 views
2

我有一個關於基本java的問題。我有一個有很多大成員的課。 我想循環這個類的所有成員。有沒有辦法呢?我如何迭代java中的所有dto成員?

public class LargeDTO extends CoreDTO { 
    private BigDecimal price1; 
    private BigDecimal price2; 
    private BigDecimal price3; 
    private BigDecimal price4; 
    private BigDecimal price5; 
    private BigDecimal price6; 
    ... 
    // getter & setter 
} 

public class UseLoop{ 
    LargeDTO largeDTO = fillLatgeDTO(); 
    BigDecimal total = BigDecimal.Zero; 
    // Is it possible ? 
    for(each member of largeDTO){ 
     total = total.add(largeDTO.getCurrentMember()); // price1, price2... 
    } 
} 
+0

可以使用一個集合的例子:'List '或通過反射 – nachokk

+0

爲什麼你以這種方式存儲價格列表而不是像List這樣的容器? – chrylis

+0

這是一個數據庫表,每個價格都是表格的一個變量。所以hibernate生成這個類。 –

回答

1

作爲替代反射API,你可以在BeanInfo類看看,的java.beans包或從Apache BeanUtils項目BeanMap類。

使用的BeanInfo

for (PropertyDescriptor propDesc : 
      Introspector.getBeanInfo(LargeDTO.class).getProperyDescriptors()) { 
    total = total.add((BigDecimal) propDesc.getReadMethod().invoke(largeDTO)); 
} 

使用BeanMap

for (Object price : new BeanMap(largeDTO).valueIterator()) { 
    total = total.add((BigDecimal) price); 
} 

Java文檔鏈接:
IntrospectorPropertyDescriptor

+0

謝謝,BeanInfo非常有用。另外,我可以像這樣獲取屬性名稱propDesc.getName(); // price1 ... –

+0

@YücelCeylan很高興爲您服務。 +1的問題。 –

0

你可以考慮使用另一種數據結構擺在首位,也就是說,如果價格在某種程度上相關,你可以將它們存儲在一個數組和遍歷這一點。或者你可以嘗試像

for (BigDecimal number:new BigDecimal[]{largeDto.getPrice1(), largeDto.getPrice2(), ...}} {...} 
3

使用Class#getDeclaredFields

Field[] fields = LargeDTO.class.getDeclaredFields(); 

或更改當前的設計有一個List<BigDecimal> prices,而不是具有相同類型的6個領域。

public class LargeDTO extends CoreDTO { 
    private List<BigDecimal> prices; 

    public LargeDTO() { 
     prices = new ArrayList<BigDecimal>(); 
    } 

    //getter and setter for your prices 
} 

//in client class... 
LargeDTO largeDTO = new LargeDTO(); 
//fill the data... 
for(BigDecimal price : largeDTO.getPrices()) { 
    //do what you want/need... 
} 
+0

我應該選擇哪種進口?而且我怎樣才能將場轉換回bigdecimal? –

+0

@YücelCeylanfor Field類,無。對於'List'和'ArrayList',使用'java.util.List'和'java.util.ArrayList'或'java.util。*'。 –

1

而是將大小數存儲在列表或映射中。或者使用反射,但這會使事情變得複雜。

+0

是的地圖似乎是這裏最明智的解決方案。 – arynaq