Java动态代理

动态代理

 

 

public interface Human {

    void info();

    void fly();
}
//被代理类
public class SuperMan implements Human {

    @Override
    public void fly() {
        System.out.println(" i can fly");
    }

    @Override
    public void info() {
        System.out.println("我是超人");
    }
}


public class MyInvocationHandler implements InvocationHandler {
    Object obj;

    public void setObj(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        HumanUtil hu = new HumanUtil();
        hu.method1();

        Object returnVal = method.invoke(obj,args);

        hu.method2();
        return returnVal;
    }
}

//代理方法
public class HumanUtil {
    public void method1(){
        System.out.println("===方法一===");
    }
    public void method2(){
        System.out.println("===方法二===");
    }
}

//代理类对象
public class MyProxy {
    public static Object getProxyInstance(Object obj){

        MyInvocationHandler mih = new MyInvocationHandler();

        mih.setObj(obj);

        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),mih);
    }
}
public class TestAOP {
    public static void main(String[] args){
         SuperMan sm = new SuperMan();
         Object obj = MyProxy.getProxyInstance(sm);
         Human h =(Human)obj;
        h.info();
        System.out.println();
        h.fly();
    }
}
 
  
  

  

posted @ 2019-04-17 16:14  鸿森  阅读(115)  评论(0编辑  收藏  举报