乐趣区

关于动态代理:动态代理

动静代理

相比于动态代理是生成代理类和实现类的 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 -------
退出移动版