java设计模式---动态代理(简单笔记) (二)

2014-11-24 11:17:36 · 作者: · 浏览: 9
RealSubject realSubject = new RealSubject();

//将目标对象交给代理
InvocationHandler handler = new DynamicProxy(realSubject);

// Class< > proxyClass = Proxy.getProxyClass(Subject.class.getClassLoader()
// , new Class[]{Subject.class});
// Subject subject = (Subject)proxyClass.getConstructor(new Class[]{InvocationHandler.class})
// .newInstance(new Object[]{handler});

//返回代理对象,相当于上面两句
Subject subject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
realSubject.getClass().getInterfaces(),
handler);

//叫代理对象去doSomething(),其实在代理对象中的doSomething()中还是会
//用handler来调用invoke(proxy, method, args) 参数proxy为调用者subject(this),
//method为doSomething(),参数为方法要传入的参数,这里没有
subject.doSomething();
}
}

打印结果:
Before Invoke ! method : public abstract void Subject.doSomething()
RealSubject.doSomething
object : RealSubject@ec6b00 result : null args : null
After Invoke !


注意:

Java动态代理涉及到的两个类:

InvocationHandler:该接口中仅定义了一个Object : invoke(Object proxy, Method method, Object[] args);参数proxy指代理类,method表示被代理的方法,args为method中的参数数组,返回值Object为代理实例的方法调用返回的值。这个抽象方法在代理类中动态实现。

Proxy:所有动态代理类的父类,提供用于创建动态代理类和实例的静态方法。