Java 动态代理

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.

可见Java的动态代理是基于Interface的。Spring AOP 功能就是利用的Java动态代理。

动态代理的用处:

  • 记入log, 在方法调用的前后记入log
  • 参数检查
  • 可以改变方法的原始行为

实现动态代理的要点:

  • 创建业务需要的Interface
  • 创建实现InvocationHandler的代理类,主要是实现invoke方法
  • 通过Proxy.newProxyInstance()生成一个实现Interface的代理类

一个例子:

package ttttt;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.management.RuntimeErrorException;

interface SomeInterface {
    public void doSomething();
}

class SomeImpl implements SomeInterface {

    @Override
    public void doSomething() {
        System.out.println("I am working!");

    }

}

class SomeProxy implements InvocationHandler {
    private SomeInterface SomeImpl;

    public SomeProxy(SomeInterface someImpl) {
        super();
        SomeImpl = someImpl;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("proxy class is " + proxy.getClass().getCanonicalName());
        System.out.println("Do something before.");
        Object object = method.invoke(SomeImpl, args);
        System.out.println("do something after.");
        return object;
    }

}

public class ProxyTest {
    public static void main(String[] args) {
        SomeInterface proxy = (SomeInterface) Proxy.newProxyInstance(SomeInterface.class.getClassLoader(),
                new Class[] { SomeInterface.class }, new SomeProxy(new SomeImpl()));
        proxy.doSomething();

    }

}

执行结果:

proxy class is ttttt.$Proxy0
Do something before.
I am working!
do something after.

参考:
Dynamic Proxy Classes
Java的动态代理(dynamic proxy)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Java动态代理 引言 最近在看AOP代码,其中利用到了Java动态代理机制来实现AOP织入。所以好好地把Java...
    草捏子阅读 5,399评论 0 18
  • 相关概念1.1 代理  在某些情况下,我们不希望或是不能直接访问对象 A,而是通过访问一个中介对象 B,由 B 去...
    天空在微笑阅读 3,130评论 0 0
  • 先看例子,demo 是一个增删改查的数据库操作,但我想在增加的这个操作上打一个日志,用来输出,可以用静态代理完成。...
    Wu巧不成阅读 1,241评论 0 1
  • 背景:学习spring的AOP或者EasyMock的源码时,需要对java的动态代理有深刻的了解 关于cglib的...
    测试你个头阅读 4,104评论 0 1
  • 生活中,我们总是会发起沟通或者成为别人沟通的对象。有些时候我们和别人沟通,可能得不到想要的反馈,但是换了另一个人去...
    小自在的园地阅读 4,479评论 0 2