Java中的自动委托
我想为将在运行时生成的对象添加一些功能.但是,这个对象的接口非常大(并且不在我的控制之下).我想将对象包装在我自己的类中,该类添加了我想要的功能并将标准接口功能委托给原始对象 - 有没有办法在 Java 中做到这一点,而无需为每个对象创建 1 行复制粘贴委托方法接口中的方法?
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?
我想避免的:
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
}
推荐答案
听起来你需要一个 动态代理 并且只拦截你想要覆盖的方法.
Sounds like you need a dynamic proxy and intercept merely the methods you want to override.
动态代理类是实现接口列表的类在运行时指定,以便通过其中一个方法调用类实例上的接口将被编码和分派通过统一的接口到另一个对象.因此,动态代理类可用于为列表创建类型安全的代理对象无需预先生成代理类的接口,例如与编译时工具一样.在一个实例上的方法调用动态代理类被分派到单个方法中实例的调用处理程序,它们被编码为java.lang.reflect.Method 对象标识的方法是调用和一个包含参数的 Object 类型的数组
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您只需创建一个方法来接收对该对象的每次调用(实际上就是您上面描述的)
By implementing InvocationHandler you simply create one method that receives every invocation on that object (effectively what you've described above)
相关文章