zoukankan      html  css  js  c++  java
  • 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动态代理”

  • 相关阅读:
    AS出现Connection timed out
    关于eclipse出现The selection cannot be launched,and there are no recent launches
    第十周周赛题解
    FJUT 2401 尼克的任务
    关于3月份的学习总结
    人生的第一题图论
    第六周周赛题解
    Drupal8 社区文档之积极的Drupal版本
    Drupal8 社区文档之Drupal安全吗
    Drupal8 社区文档之技术堆栈
  • 原文地址:https://www.cnblogs.com/shuada/p/9917700.html
Copyright © 2011-2022 走看看