Automated delegation in Java

2020-03-03 03:22发布

I would like to add some functionality to an object that will be generated at runtime. However, the interface for this object is very large (and not under my control). I would like to wrap the object in my own class which adds the functionality I want and delegates the standard interface functionality to the original object - is there any way to do this in Java without creating a 1-line copy-paste delegator method for every method in the interface?

What I want to avoid:

class MyFoo implements Foo {
  Foo wrapped;

  void myMethod() { ... }

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

What I would prefer:

class MyFoo implements Foo {
  Foo wrapped;

  void myMethod() { ... }

  // automatically delegate undefined methods to wrapped object
}

1条回答
Rolldiameter
2楼-- · 2020-03-03 03:56

Sounds like you need a dynamic proxy and intercept merely the methods you want to override.

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments

(my emphasis)

By implementing InvocationHandler you simply create one method that receives every invocation on that object (effectively what you've described above)

查看更多
登录 后发表回答