• 动态代理篇


    代理的目的,是为其他对象提供代理以控制对其的访问。在某些情况下,一个对象不能或不想访问另一个对象,此时,代理对象可以在客户端和目标对象之间起到中介的作用。

    静态代理:由程序员手写或者由工具生成代理类的源码,在程序运行前,代理类和委托类的关系已经确定。

    动态代理:很显然,是在程序运行后由java反射机制动态生成的,不存在代理类的字节码,代理类和委托类的管理在程序运行时确定。

    动态代理实例:

    目标接口TargetInterface

    public interface TargetInterface {
    
        int methodA(int n);
        int methodB(int n);
    }

    普通的实现类CommonObject

    public class CommonObject implements TargetInterface{
    
        @Override
        public int methodA(int n) {
            System.out.println("调用方法A");
            return n;
        }
    
        @Override
        public int methodB(int n) {
            System.out.println("调用方法B");
            return n;
        }
    
    }

    ProxyHandler类,实现java.lang.reflect包下的InvocationHandler,把CommonObject作为一个属性

    public class ProxyHandler implements InvocationHandler{
    
        private Object commonObject;
        
        public ProxyHandler(Object commonObject){
            this.commonObject=commonObject;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            System.out.println(proxy.getClass().getName());
            System.out.println(method.getName());
            System.out.println(args.getClass().getName());
            Object object=method.invoke(commonObject, args);
            return object;
        }
        
    }

    启用动态代理类

    public class DynamicProxy {
    
        public static void main(String[] args){
            CommonObject obj=new CommonObject();
    //        CommonObject obj2=new CommonObject();
            InvocationHandler ih=new ProxyHandler(obj);
            
            TargetInterface ti=(TargetInterface) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), ih);
            
            int n=ti.methodA(10);
            System.out.println(n);
            int m=ti.methodA(15);
            System.out.println(m);
            
    //        System.out.println();
        }
    }

    运行结果

    com.sun.proxy.$Proxy0
    methodA
    [Ljava.lang.Object;
    调用方法A
    10
    com.sun.proxy.$Proxy0
    methodA
    [Ljava.lang.Object;
    调用方法A
    15
  • 相关阅读:
    [LOJ#6284.数列分块入门8] ODT(珂朵莉树)解法
    [CF Contest] Sum of Round Numbers 题解
    基础数论记录
    [CF Contest] Kana and Dragon Quest game 题解
    hexo上怎么写博客
    keepalived的部署
    python局部和全局变量
    python发送邮件
    lamp架构的部署
    rayns数据同步
  • 原文地址:https://www.cnblogs.com/yxjdragon/p/5916448.html
Copyright © 2020-2023  润新知