美文网首页
JDK动态代理

JDK动态代理

作者: 黑咔 | 来源:发表于2020-09-11 22:50 被阅读0次
package com.test.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

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() {
            @Override
            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();

    }
}

相关文章

网友评论

      本文标题:JDK动态代理

      本文链接:https://www.haomeiwen.com/subject/gnajwctx.html