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

    JDK动态代理是基于接口的代理,下面举例说明

    • 代理类:proxy,代理动作必须要基于一个proxy实例来执行
    • 代理执行类:实现InvocationHandler,案例中是TestInvocationHandler
    • 被代理类:基于接口的用户自己的方法,案例中是SayImpl

    首先说明下InvocationHandler的invoke

    public interface InvocationHandler {
      public Object invoke(Object proxy, Method method, Object[] args)
              throws Throwable;
    }

    proxy:方法基于哪个proxy实例来执行

    method:执行proxy实例的哪个方法(proxy代理谁就执行谁的方法)

    args:methed的入参

    代码示例:

    public interface Say {
        void sayHello(String words);
    }
    public class SayImpl implements Say {
        @Override
        public void sayHello(String words) {
            System.out.println("hello:" + words);
        }
    }
    public class TestInvocationHandler implements InvocationHandler {
    
        private Object target;
        public TestInvocationHandler(Object target) {
            this.target=target;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("invoke begin");
            System.out.println("method :"+ method.getName()+" is invoked!");
            method.invoke(target,args);
            System.out.println("invoke end");
            return null;
        }
    }
        public static void main(String[] args) {
    
            TestInvocationHandler testInvocationHandler = new TestInvocationHandler(new SayImpl());
            Say say = (Say)Proxy.newProxyInstance(SayImpl.class.getClassLoader(), SayImpl.class.getInterfaces(), testInvocationHandler );
            say.sayHello("my dear");
        }

    执行结果:

    invoke begin
    method :sayHello is invoked!
    hello:my dear
    invoke end

  • 相关阅读:
    【3.1】学习C++之再逢const
    【8】学习C++之this指针
    【7】学习C++之类的构造函数
    【6】学习C++之类的实例化及访问
    【5】学习C++之类的概念
    【4】学习C++之内存管理
    【3】学习C++之const关键字的使用
    【2】学习C++之引用
    【C#第一天】数据相关
    【1】学习C++时,一些零散知识点01
  • 原文地址:https://www.cnblogs.com/cishengchongyan/p/8098607.html
Copyright © 2011-2022 走看看