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

    package cn.zr.proxy.dao;
    
    public interface PersonDao {
    
        public void eat(String name);
    }
    package cn.zr.proxy.dao.impl;
    
    import cn.zr.proxy.dao.PersonDao;
    
    public class PersonDaoImpl implements PersonDao {
    
        
        public void eat(String name) {
            System.out.println(name+"吃饭");
        }
    
    }
    package cn.zr.proxy.dao.entity;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class ProxyHandler implements InvocationHandler{
    
        //要代理的对象
        private Object proxyObject;
        
        public ProxyHandler() {
    
        }
    
        public ProxyHandler(Object proxyObject) {
            super();
            this.proxyObject = proxyObject;
        }
    
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //在代理真实对象前进行操作
            System.out.println("吃饭前,先洗手");
            
            // 代理对象调用真实对象的方法
            Object resultObj = method.invoke(proxyObject, args);
            
            //代理真实对象后进行操作
            System.err.println("吃完饭后,记得洗碗");
            return resultObj;
        }
    
    }
    package cn.zr.proxy.dao.utils;
    
    import java.lang.reflect.Proxy;
    
    import cn.zr.proxy.dao.PersonDao;
    import cn.zr.proxy.dao.entity.ProxyHandler;
    import cn.zr.proxy.dao.impl.PersonDaoImpl;
    
    public class TestUtils {
    
        public static void main(String[] args) {
            //创建实现类
            PersonDao personDao = new PersonDaoImpl();
            //创建代理类,并把真实代理对象传进去
            ProxyHandler proxyHandler = new ProxyHandler(personDao);
            //被代理的对象
            PersonDao  person = (PersonDao)Proxy.newProxyInstance(proxyHandler.getClass().getClassLoader(), personDao.getClass().getInterfaces(), proxyHandler);
            person.eat("人");
        }
    }
  • 相关阅读:
    win10去除桌面快捷方式小箭头
    java创建线程的几种方式
    Spring知识点总结
    Myeclipse运行报错:an out of memory error has occurred的解决方法
    vue-cli的使用
    3种jQuery弹出大图效果
    Weixin API -- 微信js接口
    setTimeOut传参数
    PHP的八种数据类型
    99%的人都理解错了HTTP中GET与POST的区别
  • 原文地址:https://www.cnblogs.com/lantu1989/p/6399824.html
Copyright © 2011-2022 走看看