我想向将在运行时生成的对象添加一些功能。然而,这个对象的接口(interface)非常大(而且不在我的控制之下)。我想将对象包装在我自己的类中,它添加了我想要的功能并将标准接口(interface)功能委托(delegate)给原始对象 - 有没有办法在 Java 中执行此操作而无需为每个对象创建 1 行复制粘贴委托(delegate)方法接口(interface)中的方法?
我想避免的事情:
class MyFoo implements Foo {
Foo wrapped;
void myMethod() { ... }
void interfaceMethod1() wrapped.interfaceMethod1();
int interfaceMethod2() wrapped.interfaceMethod2();
// etc etc ...
}
我更喜欢什么:
class MyFoo implements Foo {
Foo wrapped;
void myMethod() { ... }
// automatically delegate undefined methods to wrapped object
}
最佳答案
听起来你需要一个 dynamic proxy并仅拦截您想要覆盖的方法。
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
(我的重点)
通过实现 InvocationHandler您只需创建一个方法来接收对该对象的每次调用(实际上就是您上面描述的那样)
关于java - Java 中的自动委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13348215/