静态与动态代理以及动态代理代码实现

静态与动态代理以及动态代理代码实现

一.什么是代理?

为某个对象创建一个代理。以控制这个对象的访问 。代理类与实现对象类有着同一个接口或者一个父类,代理类负责请求的预处理、过滤、将请求分派给委托类处理、以及委托类执行完请求后的后续处理。

代理模式类图

这里写图片描述

二.静态代理与动态代理的区别

静态代理 所谓的静态代理程序运行前就存在代理类的字节码,也就是说代理类与实体类的关系在程序运行前就已经确定了。
动态代理 动态代理代理类的源码在程序运行期间才会创建 是通过jvm反射机制创建的就是说代理类与实体类的关系在程序运行时候才确定

三.动态代理代码实现
首先定义要使用proxy的一个接口
public interface HelloWorld {
    void hello(String str);
}
然后定义接口的实现类
public class HelloWorldImpl implements HelloWorld{
    public void hello(String str) {
        System.out.println("hello:"+str);
    }
}
建立一个动态代理类 也就是要为我们的HelloWorld实现的代理方法
public class DynamicProxyTest implements InvocationHandler {
//    要实现动态代理需要实现InvocationHandler接口
    private Object HelloWorld;

    public DynamicProxyTest(Object helloWorld) {
        HelloWorld = helloWorld;
    }
     /*
       当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用(关键)
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("hello start===========");
        method.invoke(HelloWorld,args);
     /*
        method 的invoke方法的参数:
        obj - the object the underlying method is invoked from 需要代理的object
        args - the arguments used for the method call   方法参数
     */
        System.out.println("hello end==============");
        return null;
    }
}
Main客户端代码
public class Main {
    public static void main(String[] args) {
//        代理的对象
        HelloWorld helloWorld = new HelloWorldImpl();
//        代理处理方法
        InvocationHandler handler = new DynamicProxyTest(helloWorld);

        /* newProxyInstance 返回值含义
         * returns an instance of a proxy class for the specified interfaces
         * that dispatches method invocations to the specified invocation
         * handler. 返回一个代理对象类型
         */
        HelloWorld h = (HelloWorld) Proxy.newProxyInstance(helloWorld.getClass().getClassLoader(),helloWorld.getClass().getInterfaces(),handler);
        /*
         public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
newProxyInstance 的第一个参数 loader - the class loader to define the proxy class,第二个参数 interfaces - the list of interfaces for the proxy class to implement 代理类去实现的接口列表,第三个参数 h  - the invocation handler to dispatch method invocations to 将方法调用分派到 DynamicProxyTest
         */
        h.hello("java");
        //调用HelloWord的方法
    }
}
实验结果

————hello start————
hello:java
————hello end————

Process finished with exit code 0

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值