我有一个关于基本java的问题。我有一个类,它有很多 bigdecimal 成员。 我想通过循环迭代此类的所有成员。有什么办法吗?
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...
}
}
最佳答案
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...
}
关于java - 如何在java中迭代dto的所有成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18047226/