我想避免的:
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 }
解决方法
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,您只需创建一个接收该对象上每次调用的方法(实际上您已经在上面描述过)