Most efficient way to prevent an infinite recursion in toString()?

前端 未结 9 1518
南方客
南方客 2020-12-15 21:20

To string on a collection can get into a infinite loop if somewhere in the graph of collected items is a reference back to itself. See example below.

Yes, good cod

9条回答
  •  误落风尘
    2020-12-15 21:50

    If you want to go overboard, you could use an aspect that tracks nested collections whenever you call toString().

    public aspect ToStringTracker() {
      Stack collections = new Stack();
    
      around( java.util.Collection c ): call(String java.util.Collection+.toString()) && target(c) {
        if (collections.contains(c)) { return "recursion"; }
        else { 
          collections.push(c);
          String r = c.toString(); 
          collections.pop();
          return r;
        }
      }
    }
    

    I'm never 100% on syntax without throwing this into Eclipse, but I think you get the idea

提交回复
热议问题