Java基础巩固系列 动态代理与AOP(面向切面)
概述:
代码示例:
interface Human { void info(); void fly(); } //被代理类 class SuperMan implements Human { @Override public void info() { System.out.println("我是蜘蛛侠!"); } @Override public void fly() { System.out.println("I believe I can fly!"); } } class HumanUtil { public void method1() { System.out.println("=====方法二======"); } public void method2() { System.out.println("=====方法二======"); } } class MyInvocationHandler1 implements InvocationHandler { Object obj; //被代理类对象的声明 public void setObject(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HumanUtil h = new HumanUtil(); h.method1(); Object returnVal = method.invoke(obj, args); h.method2(); return returnVal; } } class MyProxy { //动态的创建一个代理类的对象 public static Object getProxyInstance(Object obj) { MyInvocationHandler1 handler1 = new MyInvocationHandler1(); handler1.setObject(obj); return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler1); } } public class TestAOP { public static void main(String[] args) { SuperMan man = new SuperMan(); //创建一个被代理类的对象 Object obj = MyProxy.getProxyInstance(man);//返回一个代理类的对象 Human human = (Human) obj; human.info(); //通过代理类的对象调用重写的重现方法 System.out.println(); human.fly(); System.out.println(); //**************** NikeClothFactory nike = new NikeClothFactory(); Object obj1 = MyProxy.getProxyInstance(nike); ClothFactory cloth = (ClothFactory) obj1; cloth.productCloth(); } }
结果:
=====方法一======
我是蜘蛛侠!
=====方法二===========方法一======
I believe I can fly!
=====方法二===========方法一======
Nike工厂生产一批衣服
=====方法二======
图片示例: