AOP动态代理实例

来源:互联网 发布:java无限循环代码 编辑:程序博客网 时间:2024/06/07 07:51

AOP动态代理实例

package test.aop;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;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 MyInvocationHandler 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){        MyInvocationHandler handler = new MyInvocationHandler();        handler.setObject(obj);        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);    }}public class TestAOP {    public static void main(String[] args) {        //创建了一个被代理类的对象        SuperMan man = new SuperMan();        //返回一个代理类的对象        Object obj = MyProxy.getProxyInstance(man);        Human hu = (Human)obj;        //通过代理类的对象调用重写的抽象方法        hu.info();        System.out.println();        hu.fly();    }}
//结果如下--------方法一-----------我是超人!我怕谁!--------方法二----------------------方法一-----------I believe I can fly!--------方法二--------------
0 0
原创粉丝点击