动态代理的好处是实现阶段不关心代理的对象。Spring的AOP就是用动态代理来实现的。
动态代理类要实现InvocationHandler接口
- public class MyProxy implements InvocationHandler {
- Object obj = null;
- public MyProxy(Object o){
- obj = o;
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- //before
- System.out.println("before");
- method.invoke(obj, args);
- //after
- System.out.println("after");
- return null;
- }
- }
可以在方法执行前后进行其它操作,就是实现AOP了。
被代理的对象:
- public interface IReq {
- void test();
- }
- public class ObjReq implements IReq {
- @Override
- public void test() {
- System.out.println("test");
- }
- }
测试:
- public class Client {
- /**
- * @param args
- */
- public static void main(String[] args) {
- ObjReq req = new ObjReq();
- InvocationHandler handler = new MyProxy(req);
- IReq proxy = (IReq)java.lang.reflect.Proxy.newProxyInstance(
- req.getClass().getClassLoader(),
- new Class[]{IReq.class},
- handler);
- proxy.test();
- }
- }
用反射的方法来实现动态代理,输出结果:
before
test
after