Automatic delegation in Java

I want to add some functionality to the objects that will be generated at run time However, the interface of this object is very large (and not under my control) I want to wrap the object in my own class, which adds the functions I want and delegates the standard interface functions to the original object - is there a way to do this in Java without creating a line of copy and paste methods in the delegate method interface for each?

What I want to avoid:

class MyFoo implements Foo {
  Foo wrapped;

  void myMethod() { ... }

  void interfaceMethod1() wrapped.interfaceMethod1();
  int interfaceMethod2() wrapped.interfaceMethod2();
  // etc etc ...
}

What do I prefer:

class MyFoo implements Foo {
  Foo wrapped;

  void myMethod() { ... }

  // automatically delegate undefined methods to wrapped object
}

Solution

It sounds like you need a dynamic proxy and only intercept the methods you want to override

(my focus)

By implementing invocationhandler, you only need to create a method that receives every call on the object (in fact, you have described it above)

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
分享
二维码
< <上一篇
下一篇>>