javadryencapsulation

Is there a way to implement the Forwarding Object pattern in Java without boilerplate code?


Since encapsulation is considered better than inheritance (according to Effective Java and other sources), there is a pattern of Forwarding an Object. (I believe the Decorator pattern is a synonym for this, but please don't yell at me if I'm wrong!)

Basically, you write code like this:

class public ForwardSomething extends Something {
   private Something something=new Something();
   public void somethingMethod1(){return  something.somethingMethod1();}
   public void somethingMethod2(){return  something.somethingMethod2();}
   /*Do same for the methods for all methods of Something that exist when you wrote      Forward Something.*/
}

So there's a lot of boilerplate code. And we all know "Don't Repeat Yourself" is ideal. Is there a good way to approach this problem, that doesn't involve the boilerplate code?


Solution

  • With interfaces you could use a dynamic proxy class or with concrete classes you can do some trickery like dynamically writing the bytecode for a new subclass with cglib (or similar like asm)