What is the shortest way to delegate non-implemented methods to an object in Java?

I am containing the “primary object” (with most of the features) within a “helper object” that will provide convenience methods. I have only an Interface available, aside from a returned object with that interface from a factory method. I am thinking a good way to “extend” this object is composition, but the problem that my superclass must implement the primary object’s interface, which would be about 600 lines of stub code.

Clearly an uncomplicated but verbose solution would be to fill out all the stubs so they merely call the primary object’s methods. Is there a better way than this in Java? In other languages I’m familiar with, there would be ways to do automatic delegation for methods that are not implemented in the helper object.


class Helper implements Interface {
    Primary primary;

    Helper(Primary _primary) {
        primary = _primary;

    void helper() {

    // 500 lines of this
    void stub() {


Original plan was to just use regular expressions to replace all the stub TODOs in Eclipse with the actual calls. Will be looking for an Eclipse tool that does this automatically though. Also, looks like extending the interface or using Proxy is better in the end, so will be pursuing that.

There are a few possiblites.

First:Use an abstract implementation that delegates the calls.

abstract class InterfaceDelegator implements Interface {
  protected final Interface primary;
  public InterfaceDelegator() {
    this.primary = primary;
  // implements all the calls as: primary.call(...)

class Helper extends InterfaceDelegator {
  // override just the methods you need

Second:Use the proxy (probably cleaner).

See: http://docs.oracle.com/javase/1.5.0/docs/guide/reflection/proxy.html

final Interface primary = ...;
return (Interface) Proxy.newProxyInstance(Inteface.class.getClassLoader(),
   new Class[] { Interface.class },
   new InvocationHandler() {
     public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
       // if m is a method that you want to change the behaviour of, return something
       // by default, delegate to the primary
       return m.invoke(primary, args);

The invocation handler will handle calls through executing a method that you have coded, an all the others would be delegated to the primary implementation. Then, you can wrap a code like this in a method or another factory.

Third:Using the IDE to generate the methods (as others pointed out)

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » What is the shortest way to delegate non-implemented methods to an object in Java?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录