经过大牛同事的一句指点立刻明白的代理实现方式,Spring Aop应该也是这么去做的。直接上代码
实现在Car的run方法之前调用star方法,在run方法之后调用stop方法。
Car类
package com.lubby.test; public class Car { public void run() { System.out.println("I am running...."); } }
Car的run方法之前和之后调用的方法
package com.lubby.test; public class Something { public void star() { System.out.println("check the car..."); } public void stop() { System.out.println("stop the car"); } }
package com.lubby.test; public class ProxyClass extends Car { @Override public void run() { Something something = new Something(); something.star(); super.run(); something.stop(); } public static void main(String[] args) { try { ProxyClass proxyClass = (ProxyClass) Class.forName("com.lubby.test.ProxyClass").newInstance(); proxyClass.run(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
check the car... I am running.... stop the car
Java代理(Aop实现的原理),布布扣,bubuko.com
原文:http://blog.csdn.net/liu00614/article/details/30462303