体现AOP思想的一个例子(InvocationHandler)
HelloWorld类:
public class HelloWorld implements HelloWorldInterface{@Overridepublic void say(String con) {System.out.println(con);}}?HelloWorldInterface接口:
public interface HelloWorldInterface {public void say(String con);}?
LogProxy类:
//代理实现接口InvocationHandler//Java动态代理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);}// 针对接口编程@Overridepublic 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;}}?TestHelloWorld类:
public class TestHelloWorld {public static void main(String[] args) {LogProxy logProxy = new LogProxy();HelloWorldInterface hf = (HelloWorldInterface)logProxy.bind(new HelloWorld());hf.say("你好");}}?