Java反射遍历嵌套对象并列出和更新字段

我有以下复杂的 POJO 类发票


public class Measure {


    private String id;

    private Float value;


    public String getId() { return id; }

    public void setId(String id) { this.id = id; }    


    public Float getValue() { return value; }

    public void setValue(Float value) { this.value = value; }


}


public class LineItem {


    private Integer lineNumber;      

    private Measure shipped;       

    private List<LineItem> lineItems;  



    public Integer getLineNumber() { return lineNumber; }

    public void setLineNumber(Integer lineNumber) { this.lineNumber = lineNumber; }


    public Measure getShipped() { return shipped; }

    public void setShipped(Measure shipped) { this.shipped = shipped; }


    public List<LineItem> getLineItems() { return lineItems; }

    public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; }


}


public class Invoice {



    private String originUid;

    private String vehicleUid;

    private List<LineItem> lineItems;


    public String getOriginUid() { return originUid; }

    public void setOriginUid(String originUid) { this.originUid = originUid; }


    public String getVehicleUid() { return vehicleUid; }

    public void setVehicleUid(String vehicleUid) { this.vehicleUid = vehicleUid; }


    public List<LineItem> getLineItems() { return lineItems; }

    public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; }



}

现在我想深入遍历每个字段,包括 Invoice 对象中的嵌套对象,并使用反射更新它们。


我可以递归调用 updateIncomingObject()。但我需要知道如何将嵌套对象从字段中取出,如注释部分所示。

如何将字段转换为对象实例?


富国沪深
浏览 601回答 1
1回答

largeQ

要访问数组的对象(用 [] 定义的字段),您可以执行以下操作:if (incomingField.getType().isArray()) {&nbsp; &nbsp;Object[] thisArray = (Object[]) incomingField.get(incomingObject);&nbsp; &nbsp;for (int k = 0; k < thisArray.length; k++) {&nbsp; &nbsp; &nbsp; Object occurrence = thisArray[k];&nbsp; &nbsp; &nbsp; Object result = updateIncomingObject(occurrence);&nbsp; &nbsp; &nbsp; thisArray[k] = result;&nbsp; &nbsp;}&nbsp; &nbsp;incomingField.set(incomingObject, thisArray);}&nbsp;要访问List的对象,您可以执行以下操作:if (List.class.isAssignableFrom(incomingField.getType())) {&nbsp; &nbsp; List<?> thisList = (List<?>) incomingField.get(incomingObject);&nbsp; &nbsp; for (int k = 0; k < thisList.size(); k++) {&nbsp; &nbsp; &nbsp; &nbsp; Object occurrence = thisList.get(k);&nbsp; &nbsp; &nbsp; &nbsp; Object result = updateIncomingObject(occurrence);&nbsp; &nbsp; &nbsp; &nbsp; thisList.set(k, occurrence);&nbsp; &nbsp; }}注意:如果在迭代数组/列表时调用updateIncomingObject并且数组/列表中的对象是数组 (Object[]),则您的方法将不会执行任何操作,因为数组 (Object[]) 的声明字段数班级为0。我希望这对你有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java