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

    package proxy.jdk;
    
    public interface UserDao {
    
        public void add();
        public void delete();
        
    }
    package proxy.jdk;
    
    public class UserDaoimpl implements UserDao{
    
        @Override
        public void add() {
            // TODO Auto-generated method stub
            System.out.println("user add success!");
        }
    
        @Override
        public void delete() {
            // TODO Auto-generated method stub
            System.out.println("user delete success!");
        }
    
    }
    package proxy.jdk;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class Handler implements InvocationHandler{
    
        public Object target;
        
        public Handler(Object target) {
            super();
            this.target = target;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            // TODO Auto-generated method stub
            System.out.println("代理执行前");
            Object o = method.invoke(target, args);
            System.out.println("代理执行后");
            return o;
        }
        
        public Object getProxy() {
            return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this);
        }
    
    }
    package proxy.jdk;
    
    public class Test {
    
        public static void main(String[] args) {
            
            UserDao userDao=new UserDaoimpl();
            Handler handler=new Handler(userDao);
            UserDao userProxy = (UserDao) handler.getProxy();
            userProxy.add();
            userProxy.delete();
            
        }
    }
  • 相关阅读:
    页面可视化搭建工具前生今世
    16、Redis手动创建集群
    15、Redis的集群
    14、Redis的复制
    13、Redis的发布订阅模式
    12、Redis的事务
    11、Redis的持久化(RDB、AOF)
    9、Redis处理过期keys的机制
    8、Redis中sort命令详解
    7、Redis中对ZSet类型的操作命令
  • 原文地址:https://www.cnblogs.com/Danial7777777/p/9398612.html
Copyright © 2011-2022 走看看