zoukankan      html  css  js  c++  java
  • JAVA动态代理学习

    学习了一篇文章,觉得挺好,记录一下 

    参考:https://www.cnblogs.com/gonjan-blog/p/6685611.html

     利用java实现动态代理

    package com.example.demo;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class MyinvocationHandler<T> implements InvocationHandler {
        T target;
    
        public MyinvocationHandler(T target) {
            this.target = target;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
            System.out.println("代理执行" + method.getName() + "方法");
            //可以在代理中加入任意通用方法
    
            Object result = method.invoke(target, args);
            return result;
        }
    }
    package com.example.demo;
    
    public interface Person {
        void go();
    }
    
    package com.example.demo;
    
    public class Student implements Person {
        @Override
        public void go() {
            System.out.println("奔跑吧");
        }
    }

    调用执行:

       public static void main(String[] args) {
            Person st = new Student();
            InvocationHandler in = new MyinvocationHandler<Person>(st);
            Person stproxy = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(), new Class<?>[]{Person.class}, in);
            stproxy.go();
        }

    执行结果:

  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    落忆枫音(我们终将成为”枫音乡的过客“)
    PID221 / 烦人的幻灯片☆ x
    codevs 5971 打击犯罪 x
    洛谷 P2330 [SCOI2005] 繁忙的都市 x
  • 原文地址:https://www.cnblogs.com/zhanglifeng/p/11978620.html
Copyright © 2011-2022 走看看