Recursive BeanUtils.describe()

后端 未结 3 1702
南笙
南笙 2020-12-31 06:45

Is there a version of BeanUtils.describe(customer) that recursively calls the describe() method on the complex attributes of \'customer\'.

class Customer {

         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-31 07:16

    The challenge (or show stopper) is problem that we have to deal with an object graph instead of a simple tree. A graph may contain cycles and that requires to develop some custom rules or requirements for the stop criteria inside the recursive algorithm.

    Have a look at a dead simple bean (a tree structure, getters are assumed but not shown):

    public class Node {
       private Node parent;
       private Node left;
       private Node right;
    }
    

    and initialize it like this:

            root
            /  \
           A    B
    

    Now call a describe on root. A non-recursive call would result in

    {parent=null, left=A, right=B}
    

    A recursive call instead would do a

    1: describe(root) =>
    2: {parent=describe(null), left=describe(A), right=describe(B)} =>
    3: {parent=null, 
         {A.parent=describe(root), A.left=describe(null), A.right= describe(null)}
         {B.parent=describe(root), B.left=describe(null), B.right= describe(null)}}
    

    and run into a StackOverflowError because describe is called with objects root, A and B over and over again.

    One solution for a custom implementation could be to remember all objects that have been described so far (record those instances in a set, stop if set.contains(bean) return true) and store some kind of link in your result object.

提交回复
热议问题