Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Creating a circular reference between two objects in Java (See related posts)

This is in some sense the 'right' way of doing it as far as I can figure. Nothing else I've been able to come up with works even close to as well.

public class LazyModules 
{
  static int i = 0;

  static abstract class A{
    abstract B getB();
    int k = i++;
    public String toString() { return "" + k; }
  }

  static abstract class B{
    abstract A getA();
    int k = i++;
    public String toString() { return "" + k; }
  }

  public static void doStuff(A foo, B bar){
    System.out.println("foo = " + foo);
    System.out.println("foo.b = " + foo.getB());
    System.out.println("bar = " + bar);
    System.out.println("bar.a = " + bar.getA()); 
  }

  public static void main(String[] args){
    new Object(){
      final A foo = new A() { B getB() { return bar; }  };
      final B bar = new B() { A getA() { return foo; }  };

      { doStuff(foo, bar); }
    };
  }
}


You need to create an account or log in to post comments to this site.


Click here to browse all 5201 code snippets

Related Posts