我有一个XML解析的pojo,如下
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"activity",
"orderDetails"
})
@XmlRootElement(name = "GxML")
public class GxML {
@XmlElement(name = "Activity", required = true)
public String activity;
@XmlElement(name = "OrderDetails", required = true)
public GxML.OrderDetails orderDetails;
//get set
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"initiatorRole",
"productDetails"
})
public static class OrderDetails {
@XmlElement(name = "InitiatorRole", required = true)
public String initiatorRole;
//get set
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"product"
})
public static class ProductDetails {
@XmlElement(name = "Product", required = true)
public List<GxML.OrderDetails.ProductDetails.Product> product;
public List<GxML.OrderDetails.ProductDetails.Product> getProduct() {
if (product == null) {
product = new ArrayList<GxML.OrderDetails.ProductDetails.Product>();
}
return this.product;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"quantity",
"commodity"
})
public static class Product {
@XmlElement(name = "Quantity", required = true)
public BigDecimal quantity;
@XmlElement(name = "Commodity", required = true)
public String commodity;
//get set
}}}}
我需要使用Java反射获取所有字段名称及其相应的值
Class c1 = gXml.getClass();
Field[] valueObjFields = c1.getDeclaredFields()[1].getType().getDeclaredFields();
for (int i = 0; i < valueObjFields.length; i++) {
String fieldName = valueObjFields[i].getName();
valueObjFields[i].setAccessible(true);
Object newObj = valueObjFields[i].get(gXml.getOrderDetails());
orderMap.put(valueObjFields[i].getAnnotation(XmlElement.class).name(), newObj);
if("productDetails".equalsIgnoreCase(fieldName)){
Class c2 = gXml.getOrderDetails().getProductDetails().getProduct().get(0).getClass();
Field[] valueObjFields1 = c2.getDeclaredFields();
for (int j = 0; j < valueObjFields1.length; j++) {
String fieldName2 = valueObjFields1[j].getName();
valueObjFields1[j].setAccessible(true);
Object newObj2 = valueObjFields1[j].get(gXml.getOrderDetails().getProductDetails().getProduct());
orderMap.put(valueObjFields1[j].getAnnotation(XmlElement.class).name(), newObj2);
} } }
对于订单详细信息,它运行良好,但在获取数量和商品的产品详细信息中,它在
处给出了非法参数异常对象newObj2=valueObjFields1[j].get(gXml.getOrderDetails().getProductDetails().getProduct());
如何使用反射获取列表值。
您可以从getProduct().get(0)
类(看起来像列表的成员)中获得字段
Class c2 = gXml.getOrderDetails().getProductDetails().getProduct().get(0).getClass();
Field[] valueObjFields1 = c2.getDeclaredFields();
但是尝试从集合本身读取值(而不是获取(0)元素)
valueObjFields1[j].get(gXml.getOrderDetails().getProductDetails().getProduct());