java 动态代理

场景简单描述:对交通工具的监控,记录交通工具移动花费的时间。

现在我们定于一个交通工具接口:

public interface IMoveable {
    void move();
}

交通工具包含一个move方法。

然后定义一种具体的交通工具,以小汽车为例:

public class Car implements IMoveable {

    @Override
    public void move() {
        //实现开车
        try {
            Thread.sleep(new Random().nextInt(1000));
            System.out.println("汽车行驶中....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

想要监控小汽车移动花费的时间,最简单的方法是在move的前后加上监控处理。但是不推荐,原因详细大家都懂的。

因此我们可能需要定义一个代理类,在代理类中调用car 的 move方法,代码如下:

public class CarProxy {

    public void move(IMoveable car) {
        long starttime = System.currentTimeMillis();
        System.out.println("汽车开始行驶....");
        
        car.move();
        
        long endtime = System.currentTimeMillis();
        System.out.println("汽车结束行驶....  汽车行驶时间:" 
                + (endtime - starttime) + "毫秒!");
    }

}

如果只是监控交通工具的话上面已经完全满足。但是如果我们现在不想监控交通工具了,我们要监控动物跑的时间呢,是不是又要创建其他的代理类。

这样累计下来代理类会无限多。有没有更好的解决方式呢?

重点来了。。。

我们定义一个监控时间的代理类,对所有时间类的监控处理,使用InvocationHandler 接口,代码如下:

public class TimeHandler implements InvocationHandler {

    public TimeHandler(Object target) {
        super();
        this.target = target;
    }

    private Object target;

    /*
     * 参数:
     * proxy  被代理对象
     * method  被代理对象的方法
     * args 方法的参数
     * 
     * 返回值:
     * Object  方法的返回值
     * */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        long starttime = System.currentTimeMillis();
        System.out.println("开始.........");
        method.invoke(target);
        long endtime = System.currentTimeMillis();
        System.out.println("结束.........  时间:" 
                + (endtime - starttime) + "毫秒!");
        return null;
    }

写一个测试方法来试试上面的代理类吧,看看效果如何:

public class Test {

    /**
     * JDK动态代理测试类
     */
    public static void main(String[] args) {
        Car car = new Car();
        InvocationHandler h = new TimeHandler(car);
        Class<?> cls = car.getClass();
        /**
         * loader  类加载器
         * interfaces  实现接口
         * h InvocationHandler
         */
        IMoveable m = (IMoveable)Proxy.newProxyInstance(cls.getClassLoader(),
                                                cls.getInterfaces(), h);
        m.move();
    }

}

现在所有想监控时间的都可以使用TimeHandler啦,只需要给代理传入不同的参数即可!!!

注:使用java动态代理,对象必须实现某个接口。

原文地址:https://www.cnblogs.com/rmsSpring/p/4584123.html