
也许动态
Proxy的Java可以帮助您。因此,仅当您使用接口时,它才起作用。在这种情况下,我将调用接口
MyInterface并设置默认实现:
public class MyClass implements MyInterface { @Override public void method1() { System.out.println("foo1"); } @Override public void method2() { System.out.println("foo2"); } @Override public void methodN() { System.out.println("fooN"); } public static void main(String[] args) { MyClass wrapped = new MyClass(); wrapped.method1(); wrapped.method2(); MyInterface wrapper = WrapperClass.wrap(wrapped); wrapper.method1(); wrapper.method2(); }}包装类的实现如下所示:
public class WrapperClass extends MyClass implements MyInterface, InvocationHandler { private final MyClass delegate; public WrapperClass(MyClass delegate) { this.delegate = delegate; } public static MyInterface wrap(MyClass wrapped) { return (MyInterface) Proxy.newProxyInstance(MyClass.class.getClassLoader(), new Class[] { MyInterface.class }, new WrapperClass(wrapped)); } //you may skip this definition, it is only for demonstration public void method1() { System.out.println("bar"); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Method m = findMethod(this.getClass(), method); if (m != null) { return m.invoke(this, args); } m = findMethod(delegate.getClass(), method); if (m != null) { return m.invoke(delegate, args); } return null; } private Method findMethod(Class<?> clazz, Method method) throws Throwable { try { return clazz.getDeclaredMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException e) { return null; } }}请注意该类:
- extends
MyClass
,以继承默认实现(其他任何方法都可以) - 实现
Invocationhandler
,以允许代理进行反射 - 可选实现
MyInterface
(以满足装饰器模式)
此解决方案使您可以覆盖特殊方法,但可以委派所有其他方法。这甚至可以与Wrapper类的子类一起使用。
请注意,该方法
findMethod尚未捕获特殊情况。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)