zoukankan      html  css  js  c++  java
  • Java-基于JDK的动态代理

    原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/11686615.html

      简单的记录一下Java中自带动态代理的用法.

      准备材料: 

        1.一个接口

        2.一个实现了接口的类

        3.一个动态代理类

        4.一个测试类

    package dynamicProxy;
    
    /**
     * 生物
     */
    public interface Creature {
        void move();
    }
    package dynamicProxy;
    
    /**
     * 人类
     */
    public class Human implements Creature {
    
        @Override
        public void move() {
            System.out.println("human is move! ");
        }
    }
    package dynamicProxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    /**
     * 生物的动态代理类
     */
    public class DynamicProxyCreature implements InvocationHandler {
    
        private Creature creature;
    
        public Object newInstance(Creature creature){
            this.creature = creature;
            return Proxy.newProxyInstance(this.creature.getClass().getClassLoader(), this.creature.getClass().getInterfaces(), this);
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("代理部分开始工作了......");
            this.creature.move();
            System.out.println("代理部分结束工作了......");
            return null;
        }
    }
    package dynamicProxy;
    
    /**
     * 测试一下
     */
    public class MainTest {
        public static void main(String[] args) {
            DynamicProxyCreature dynamicProxyCreature = new DynamicProxyCreature();
            Creature obj = (Creature) dynamicProxyCreature.newInstance(new Human());
            obj.move();
        }
    }

      通过Proxy生成一个新的对象, 再调用对象方法时可以在方法前后进行另外的操作处理, 调用的对象也是基于接口的,而不是实现类的.

  • 相关阅读:
    selenium 18种元素定位方法
    python3+selenium配置可能报错记录
    adb+monkey压力测试入门
    appscan使用教程(全)
    appium---android元素定位
    QTP自动化测试
    postman Could not get any response。
    Jmeter接口测试+压力测试
    Android 偏门xml属性
    CrashHandler
  • 原文地址:https://www.cnblogs.com/fanerwei222/p/11686615.html
Copyright © 2011-2022 走看看