如何在java中迭代dto的所有成员?
我对基本java有一个问题。我有一个类,它有很多bigdecimal成员。 我想通过循环迭代这个类的所有成员。有什么办法吗如何在java中迭代dto的所有成员?,java,Java,我对基本java有一个问题。我有一个类,它有很多bigdecimal成员。 我想通过循环迭代这个类的所有成员。有什么办法吗 public class LargeDTO extends CoreDTO { private BigDecimal price1; private BigDecimal price2; private BigDecimal price3; private BigDecimal price4; private BigDecimal p
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...
}
}
<>你可以考虑首先使用另一个数据结构,也就是说,如果价格有某种关系,你可以把它们存储在一个数组中,然后迭代。或者你可以试试类似的东西
for (BigDecimal number:new BigDecimal[]{largeDto.getPrice1(), largeDto.getPrice2(), ...}} {...}
使用
或者将当前设计更改为具有价目表
,而不是具有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...
}
公共类LargeDTO扩展了CoreDTO{
私人标价;
公共大户{
价格=新的ArrayList();
}
//获取和设定您的价格
}
//在客户端类中。。。
LargeDTO LargeDTO=新的LargeDTO();
//填写数据。。。
for(BigDecimal价格:largeDTO.getPrices()){
//做你想要/需要的。。。
}
您可以使用java反射:Class.getDeclaredFields()
()并检查结果字段数组。将大小数存储在列表或映射中。或者使用反射,但这会使事情变得不必要的复杂。作为反射API的替代方案,您可以查看java.beans包中的类或项目中的类
使用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文档链接到:,您可以使用一个集合示例:
List
或通过反射为什么要以这种方式存储价格列表,而不是使用类似于List
的容器?这是一个DB表,每个价格都是该表的一个列。所以hibernate生成这个类。getfields
不会检索私有字段。是的,映射似乎是这里最明智的解决方案。我应该选择哪个导入?我如何将字段转换回bigdecimal?@YücelCeylan for字段
类,无。对于List
和ArrayList
,请使用java.util.List
和java.util.ArrayList
或java.util.*
。谢谢,BeanInfo非常有用。此外,我还可以获得如下属性名:propDesc.getName();//价格1…@YücelCeylan很高兴能帮上忙+1.对问题的答复。
for (Object price : new BeanMap(largeDTO).valueIterator()) {
total = total.add((BigDecimal) price);
}