Java动态代理

来源:互联网 发布:思迅软件合作伙伴社区 编辑:程序博客网 时间:2024/05/22 05:11

看java核心技术的时候,感觉动态代理没有理解好,于是查找了一些文档,写下这篇文章

首先,你需要熟悉代理模式,至少是静态代理,才可以很快理解这篇文章。

Dynamic Proxy是在运行时生成的class,在生成它时你必须提供一 组interface给它,然后该class就宣称它实现了这些 interface。你当然可以把该class的实 例当作这些interface中的任何一个来用。当然啦,这个Dynamic Proxy其实就是一个Proxy, 它不会替你作实质性的工作,在生成它的实例时你必须提供一个handler,由它接管实际的工 作。

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. It can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class. Dynamic proxy classes are useful to an application or library that needs to provide type-safe reflective dispatch of invocations on objects that present interface APIs.

通过动态代理技术,可以很方便地实现类似Spring AOP一样的方法拦截器

public interface Foo {    Object bar(Object obj) throws BazException;}public class FooImpl implements Foo {    Object bar(Object obj) throws BazException {        // ...    }}public class DebugProxy implements java.lang.reflect.InvocationHandler {    private Object obj;    public static Object newInstance(Object obj) {        return java.lang.reflect.Proxy.newProxyInstance(            obj.getClass().getClassLoader(),            obj.getClass().getInterfaces(),            new DebugProxy(obj));    }    private DebugProxy(Object obj) {        this.obj = obj;    }    public Object invoke(Object proxy, Method m, Object[] args)        throws Throwable    {        Object result;        try {            System.out.println("before method " + m.getName());            result = m.invoke(obj, args);        } catch (InvocationTargetException e) {            throw e.getTargetException();        } catch (Exception e) {            throw new RuntimeException("unexpected invocation exception: " +                                       e.getMessage());        } finally {            System.out.println("after method " + m.getName());        }        return result;    }}

参考文献

java代理机制
oracle doc

0 0
原创粉丝点击