动态代理

动态代理

相比于静态代理是生成代理类和实现类的class文件,动态代理则是动态生成字节码加载到程序中。而且,相比于静态代理需要针对每一个接口去单独写一个代理类,动态代理只需要一个代理类就可以实现(根据传入的被代理类判断)

JDK动态代理

public interface Player {
    void getGamePoints();
}

public class ADavids implements Player {
    private String name = "Anthony Davids";
    public void getGamePoints() {
        System.out.println(name + " get 45 points!");
    } 
}

public class ProxyHandler implements InvocationHandler {
    private Object object;
    public ProxyHandler(Object object){
        this.object = object;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName());
        System.out.println("The player is Coming-------" );
        Object obj = method.invoke(object,args);
        System.out.println("THE END---------------");
        return obj;
    }
}


public class Test {
    public static void main(String[] args) {
        //JDK动态代理
        ADavids aDavids = new ADavids();
        Object obj = Proxy.newProxyInstance(aDavids.getClass().getClassLoader(),aDavids.getClass().getInterfaces(),new ProxyHandler(aDavids));
        Player proxyAfterObj = (Player)obj;
        proxyAfterObj.getGamePoints();
    }
}

打印结果为:
getGamePoints
The player is Coming-------
Anthony Davids get 45 points!
THE END---------------

CGLIB动态代理

public class EspnNews {
    public void playnews(){
        System.out.println("AD GET 45 PTS TODAY");
    }
}


public class InterceptorTv implements MethodInterceptor {
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("This dailynew -------");
        Object obj = methodProxy.invokeSuper(o,objects);
        System.out.println("Play End -------");
        return obj;
    }
}


public class ProxyNews {
    public static Object getProxyObj(Class clazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new InterceptorTv());
        return enhancer.create();
    }
}


public class Test {
    public static void main(String[] args) {
        //CGlib动态代理
        EspnNews espnNews = (EspnNews) ProxyNews.getProxyObj(EspnNews.class);
        espnNews.playnews();
    }
}

打印结果为:
This dailynew -------
AD GET 45 PTS TODAY
Play End -------

你可能感兴趣的:(动态代理)