What is the shortest way to delegate an unimplemented method to an object contained in Java? [waiting for answer]

I include the primary object (with most functions) in helpers, which will provide a convenient method I have only one interface available, except for the interface between the returned object and the factory method I'm thinking that a good way to "extend" this object is composition, but my superclass must implement the main object interface. This will be about 600 lines of stub code

Obviously, a simple but tedious solution is to fill in all stubs so that they only call the methods of the main object Is there a better way than this in Java? In other languages I'm familiar with, there are ways to perform automatic delegation for methods that are not implemented in helper objects

Example:

class Helper implements Interface {
    Primary primary;

    Helper(Primary _primary) {
        primary = _primary;
    }

    void helper() {
        doStuff();
    }

    // 500 lines of this
    void stub() {
        primary.stub();
    }
}

be careful:

The original plan was to replace all stub todo in eclipse with actual calls using regular expressions We'll look for an eclipse tool that does this automatically In addition, it seems that extending interfaces or using agents is ultimately better, so it will be pursued

Solution

There are some possibilities

First: use the abstract implementation of delegate invocation

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 an agent (possibly 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 call handler will handle the call by executing your encoded method, and all other methods will be delegated to the main implementation You can then wrap such code in a method or other factory

Third: use ide generation methods (as others pointed out)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>