aop,基于jdk的动态代理

 

复制代码
public class ProxyTest {
    public static void main(String[] args) {
        //创建目标对象
        final Target target = new Target();
        //获得增强对象
        final Advice advice = new Advice();
        //返回值  就是动态生成的代理对象
        TargetInterface proxy = (TargetInterface)Proxy.newProxyInstance(
        target.getClass().getClassLoader(),//目标对象加载器
        target.getClass().getInterfaces(),//目标对象相同的接口字节码对象数组
        new InvocationHandler() {
            // 调用代理对象的任何方法  实质执行的都是invoke方法
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //前置增强
                advice.before();
                //执行目标方法
                Object invoke = method.invoke(target, args);
                //后置增强
                advice.afterReturning();
                return invoke;
            }
        }
                );
        
        //调用代理对象的方法
        proxy.save();
        
    }
}
复制代码

 

posted @   Cuora  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示