首页 > 编程 > Java > 正文

Java动态代理

2019-11-09 16:34:51
字体:
来源:转载
供稿:网友
概述:动态代理其实就是java.lang.reflect.PRoxy类动态的生成一个class byte,该class会继承Proxy类,并且会实现所有你指定的接口(参数中传入的接口数组)。然后利用你指定的classloader将class byte加载进jvm,最后生成这样一个类的对象,并初始化该对象的一些值,初始化之后将对象返回给调用的客户端。作用:动态代理能够在你的核心业务方法前后做一些你想做的辅助工作,如log日志、安全机制等。实例分析:Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service }, new InvocationHandler() { private final Platform platform = Platform.get(); @Override public Object invoke(Object proxy, Method method, Object... args) throws Throwable {            // 可以在这里写一些核心业务之前的方法            System.out.print("you can do something before you business");            Object result = method.invoke(this, args);            // 可以在这里写一些核心业务之前的方法            System.out.print("you can do something after you business");            return result; } });invoke(Object proxy,Method method,Object... args)三个参数分别代表的意思是:proxy:指代我们所代理的那个真实对象method:指代我们所要调用真实对象的某个方法的Method对象args:指代我们调用某个真实方法时接受的参数运行先后顺序如下:You can do something here before process your business核心业务method...You can do something here after process your business
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表