• 动态代理


    主营业务接口:

    public interface IUserManger {
        public void AddUser(String UserName, String Password);
        public void ModifyUser(int id, String UserName, String Password);
    
    }

    接口实现类:

    public class UserManagerImpl implements IUserManager{
    
    
        public void addUser(String username, String password) {
            System.out.println("=========UserManagerImpl.addUser()===========");
        }
    
        public void modifyUser(int id, String username, String password) {
            System.out.println("=========UserManagerImpl.modifyUser()===========");
        }
    }

    继承invocationHandler的类:

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    //帮助我们动态的生成代理对象JDK1.5
    
    public class SecurityHandler implements InvocationHandler {
    
        private Object targetObject;//目标对象
    
        //生成代理对象
        public Object proxyInstance(Object paramObject){
            this.targetObject = paramObject;
            return Proxy.newProxyInstance(
                    this.targetObject.getClass().getClassLoader(),
                    this.targetObject.getClass().getInterfaces(),
                    this);//得到目标加载器实现invocationHandler的类,也就是本类
        }
    
        //传入代理对象,目标对象的方法,方法参数,代理方法与目标方法都实现了IUserManager
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object resultObj = null;
            checkSecurity();
            try{
                resultObj = method.invoke(this.targetObject,args);//递归调用
            }catch (Exception ex){
                ex.printStackTrace();
            }
            return resultObj;
        }
    
        public void checkSecurity(){
            System.out.println("=======checkSecurity()==========");
        }
    }

    测试类:

    public class Client {
    
        public static void main(String[] args) {
            SecurityHandler securityHandler = new SecurityHandler();
            IUserManager iUserManager = (IUserManager) securityHandler.proxyInstance(new UserManagerImpl());
            iUserManager.addUser("abc","123");
    
        }
    }
  • 相关阅读:
    允许debian wheezy支持IOS7+的iphone.
    openSUSE 国内镜像摘要
    策略模式总结
    顺序串
    WindowState注意事项
    NLP | 自然语言处理
    Using Autorelease Pool Blocks
    NSAutoreleasePool & thread
    oc语言特性
    oc语言基础整理
  • 原文地址:https://www.cnblogs.com/hetaoyuan/p/12511141.html
Copyright © 2020-2023  润新知