Java动态代理

代理可以将额外的操作和实际对象分离,类似于一个中间人的角色,使用基类或接口作为参数,这样在需求有变动时就很容易修改,也可以在代理中监控各个方法的调用。 以下代码摘自《Think in Java》 接口Interface.java:

public interface Interface {
    void doSomething();
    void somethingElse(String arg);
}

实现 RealObject.java:

public class RealObject implements Interface {

    @Override
    public void doSomething() {
        // TODO Auto-generated method stub
        System.out.println("doSomething");
    }

    @Override
    public void somethingElse(String arg) {
        // TODO Auto-generated method stub
        System.out.println("somethingElse"+arg);

    }

}

SimpleProxy.java:

/**
 * 简单的代理模式,把对象隐藏起来,通过自身暴露的方法来调用
 *
 */
public class SimpleProxy {
    private Interface proxied;
    public SimpleProxy(Interface proxied)
    {
        this.proxied=proxied;
    }
    public void doSomething() {
        System.out.println("SimpleProxy doSomething");
        proxied.doSomething();
    }

    public void somethingElse(String arg) {
        System.out.println("SimpleProxy SomethingElse"+arg);
        proxied.somethingElse(arg);
    }
}

动态代理操作,支持任意对象方法的调用 DynamicProxyHandler.java:

public class DynamicProxyHandler implements InvocationHandler {
    private Object proxied;
    public DynamicProxyHandler(Object proxied)
    {
        this.proxied=proxied;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        // TODO Auto-generated method stub
        if(args!=null)
        {
            for(Object arg:args)
            {
                System.out.println(" arg"+arg);
            }
        }
        return method.invoke(proxied, args);
    }
}

使用方法 SimpleDynamicProxy.java:

public class SimpleDynamicProxy {
    public static void main(String[] args)
    {
        //代理
        RealObject real=new RealObject();
        SimpleProxy simpleProxy=new SimpleProxy(real);
        simpleProxy.doSomething();
        simpleProxy.somethingElse("bonobo");
        //动态代理
        Interface proxy=(Interface)Proxy.newProxyInstance(Interface.class.getClassLoader(),new Class[]{Interface.class}, new DynamicProxyHandler(real));
        proxy.doSomething();
        proxy.somethingElse("bonobo");
    }
}