zoukankan      html  css  js  c++  java
  • 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();
        }
    }
     
      
      
    

      

  • 相关阅读:
    CRB and His Birthday(2015多校)
    B. Bear and Three Musketeers
    Uva657
    cas服务端改造
    有用的maven插件
    maven管理的非标准目录
    struts2中的action交由spring管理
    数据库分库
    linux内核系列之二_资源
    linux内核系列之一_工具
  • 原文地址:https://www.cnblogs.com/yangHS/p/10724264.html
Copyright © 2011-2022 走看看