标签:
订单类
public class Order{ private String sn; /** 订单项 */ private List<OrderItem> orderItems = new ArrayList<OrderItem>(); ... get set方法 ... }
订单项类
public class OrderItem{ /** 商品编号 */ private String sn; /** 商品名称 */ private String name; ... get set方法 ... }
在利用BeanUtils.getProperty取得数据时
Order order = getOrder(); String[] properties = {"sn","orderItems[0].name""} for (int i = 0; i < properties.length; i++) { System.out.println(BeanUtils.getProperty(Order,properties[i]);); }
取得集合orderItems的相关数据时,利用BeanUtils.getProperty(Object bean, String name) 方法,必须有集合的索引(orderItems[0]),如果想把orderItems全部数据输出,BeanUtils.getProperty做不到;
orderItems为空是,还会报空指针异常,我想到了下面这种比较笨的方法:
Order order = getOrder(); String[] properties = {"sn","orderItems"} for (int i = 0; i < properties.length; i++) { System.out.println(BeanUtils.getProperty(Order,properties[i]);); StringBuilder stringBuilder = new StringBuilder(); if(properties[i].equals("orderItems")){ // 属性为订单项集合时 StringBuilder stringBuilder = new StringBuilder(); List<OrderItem> orderItemList = order.getOrderItems(); for(OrderItem orderItem:orderItemList){ stringBuilder = stringBuilder.append(orderItem.name() ); stringBuilder = stringBuilder.append(" | "); } } }
标签:
原文地址:http://www.cnblogs.com/runyu/p/4958230.html