debugproxy.java
来自「23种GOF模式的java代码实现」· Java 代码 · 共 45 行
JAVA
45 行
package org.gof.structure.proxy;
public class DebugProxy
implements java.lang.reflect.InvocationHandler {
private Object obj;
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new DebugProxy(obj));
}
private DebugProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, java.lang.reflect.Method m, Object[] args) throws
Throwable {
Object result;
try {
System.out.println("before method " + m.getName());
//调用Foolmpl的方法
result = m.invoke(obj, args);
}
catch (java.lang.reflect.InvocationTargetException e) {
throw e.getTargetException();
}
catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
}
finally {
System.out.println("after method " + m.getName());
}
return result;
}
public static void main(String[] args) {
Foo foo = (Foo) DebugProxy.newInstance(new FooImpl());
foo.bar(null);
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?