• Proxy.newInstance与InvocationHandler的使用示例


    先定义一个接口,根据代理模式的原理,被代理类与代理类都要实现它。

    public interface Person {
        void eat();
    }

    再写一个实际执行任务的类(被代理类):

    public class RealPerson implements Person {
        @Override
        public void eat() {
            System.out.println("I am eating");
        }
    }

    代理类的写法:写一个InvocationHandler的子类

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class PersonProxyHandler implements InvocationHandler {
        private Person man;
    
        public PersonProxyHandler(Person man) {
            this.man = man;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("before eating");
            Object res = method.invoke(man, args);
            System.out.println("after eating");
            return res;
        }
    
    }

    按照常规想法,代理类要拥有一个被代理类对象的引用,然后在invoke方法中,method.invoke(man, args); 这一句代码表明对实际对象的调用,其余代码就是AOP增强了。

    主类:

    import java.lang.reflect.Proxy;
    
    public class Solution {
    
        public static void main(String[] args) {
            RealPerson man = new RealPerson();
            PersonProxyHandler realHandler = new PersonProxyHandler(man);
    
            Person proxy = (Person) Proxy.newProxyInstance(
                    Person.class.getClassLoader(),
                    new Class[]{Person.class},
                    realHandler);
            proxy.eat();
        }
    }

    运行main方法,控制台打印如下:

    before invoke
    is eating
    after invoke

    这种代理方式也称为“JDK动态代理”

  • 相关阅读:
    eclipse中的debug模式的使用
    Hibernate快速入门
    鸟哥的 Linux 私房菜Shell Scripts篇(四)
    Vim命令图解及快捷键讲解
    SpringBoot文档
    鸟哥的 Linux 私房菜Shell Scripts篇(三)
    鸟哥的 Linux 私房菜Shell Scripts篇(二)
    (二)IDEA使用,快捷键
    (一)IDEA使用,基础配置
    idea-git同步服务器代码后撤销操作
  • 原文地址:https://www.cnblogs.com/shuada/p/9917700.html
Copyright © 2020-2023  润新知