首页 > 技术文章 > 动态代理篇

yxjdragon 2016-09-28 15:12 原文

代理的目的,是为其他对象提供代理以控制对其的访问。在某些情况下,一个对象不能或不想访问另一个对象,此时,代理对象可以在客户端和目标对象之间起到中介的作用。

静态代理:由程序员手写或者由工具生成代理类的源码,在程序运行前,代理类和委托类的关系已经确定。

动态代理:很显然,是在程序运行后由java反射机制动态生成的,不存在代理类的字节码,代理类和委托类的管理在程序运行时确定。

动态代理实例:

目标接口TargetInterface

public interface TargetInterface {

    int methodA(int n);
    int methodB(int n);
}

普通的实现类CommonObject

public class CommonObject implements TargetInterface{

    @Override
    public int methodA(int n) {
        System.out.println("调用方法A");
        return n;
    }

    @Override
    public int methodB(int n) {
        System.out.println("调用方法B");
        return n;
    }

}

ProxyHandler类,实现java.lang.reflect包下的InvocationHandler,把CommonObject作为一个属性

public class ProxyHandler implements InvocationHandler{

    private Object commonObject;
    
    public ProxyHandler(Object commonObject){
        this.commonObject=commonObject;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println(proxy.getClass().getName());
        System.out.println(method.getName());
        System.out.println(args.getClass().getName());
        Object object=method.invoke(commonObject, args);
        return object;
    }
    
}

启用动态代理类

public class DynamicProxy {

    public static void main(String[] args){
        CommonObject obj=new CommonObject();
//        CommonObject obj2=new CommonObject();
        InvocationHandler ih=new ProxyHandler(obj);
        
        TargetInterface ti=(TargetInterface) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), ih);
        
        int n=ti.methodA(10);
        System.out.println(n);
        int m=ti.methodA(15);
        System.out.println(m);
        
//        System.out.println();
    }
}

运行结果

com.sun.proxy.$Proxy0
methodA
[Ljava.lang.Object;
调用方法A
10
com.sun.proxy.$Proxy0
methodA
[Ljava.lang.Object;
调用方法A
15

 

推荐阅读