示例代码如下:
//LogProxy.java
package com.gc.action;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class LogProxy implements InvocationHandler{
private Logger logger = Logger.getLogger(this.getClass().getName());
private Object delegate;
//绑定代理对象
public Object bind(Object delegate){
this.delegate = delegate;
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
delegate.getClass().getInterfaces(),this);
}
//针对接口编程
public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {
Object result = null;
try{
//在方法调用前后进行日志输出
logger.log(Level.INFO,args[0]+" 开始审核数据...");
result = method.invoke(delegate, args);
logger.log(Level.INFO,args[0]+" 审核数据结束...");
}catch(Exception e){
logger.log(Level.INFO,e.toString());
}
return result;
}
}
//TimeBookInterface.java
package com.gc.impl;
//针对接口编程
public interface TimeBookInterface {
public void doAuditing(String name);
}
//TimeBook.java
package com.gc.action;
import com.gc.impl.TimeBookInterface;
public class TimeBook implements TimeBookInterface {
//审核数据的相关程序
public void doAuditing(String name){
System.out.println("审核程序");
}
}
//TestHelloWorld.java
package com.gc.test;
import com.gc.action.LogProxy;
import com.gc.action.TimeBook;
import com.gc.impl.TimeBookInterface;
public class TestHelloWorld {
public static void main(String[] args){
//实现了对日志类的重用
LogProxy logProxy = new LogProxy();
TimeBookInterface timeBookProxy = (TimeBookInterface)logProxy.bind(new TimeBook());
timeBookProxy.doAuditing("张三");
}
}
运行结果:
[INFO ] 2009-11-01 23:23:39 com.gc.action.LogProxy - 张三 开始审核数据...
审核程序
[INFO ] 2009-11-01 23:23:39 com.gc.action.LogProxy - 张三 审核数据结束...