zoukankan      html  css  js  c++  java
  • 动态代理

    1:利用反射机制在运行时创建代理类

    package com.wing.mall.base.proxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    /**
     * <p>
     *     利用反射机制在运行时创建代理类
     * </p>
     *
     * @author: heluwei
     * @Date: 2020/4/15 10:51
     */
    public class ProxyHandler implements InvocationHandler {
        private Object object;
        public ProxyHandler(Object object){
            this.object = object;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("Before invoke "  + method.getName());
            method.invoke(object, args);
            System.out.println("After invoke " + method.getName());
            return null;
        }
    
    }

    2:创建目标类

    package com.wing.mall.base.proxy;
    
    public interface ByeInterface {
        void sayBye();
    }
    package com.wing.mall.base.proxy;
    
    /**
     * <p></p>
     *
     * @author: heluwei
     * @Date: 2020/4/15 10:53
     */
    public class Bye implements ByeInterface {
        @Override
        public void sayBye() {
            System.out.println("Bye 张三!");
        }
    }

    使用:

    public static void main(String[] args) {
            Bye bye = new Bye();
            InvocationHandler  proxyHandler = new ProxyHandler(bye);
            ByeInterface byeProxy = (ByeInterface)Proxy.newProxyInstance(bye.getClass().getClassLoader(), bye.getClass().getInterfaces(), proxyHandler);
            byeProxy.sayBye();
        }

    输出:

     

  • 相关阅读:
    字符串的全排列

    链表
    青蛙跳一格或者两格,n格跳法
    二叉树
    Concurrent实现原理
    sql语句总结 (转) http://blog.csdn.net/fengfeng91/article/details/15029173
    ArrayList实现原理
    java虚拟机 内存分配
    【转】关于Quartus ii无法识别Modelsim路径的问题
  • 原文地址:https://www.cnblogs.com/bulrush/p/12704011.html
Copyright © 2011-2022 走看看