JDK方式的动态代理

本文介绍了使用JDK实现动态代理的四个关键步骤:创建实现InvocationHandler接口的动态处理器类,定义被代理的类和接口,通过Proxy的newProxyInstance方法生成代理对象,最后通过代理对象执行方法。

动态代理的步骤:

 1、创建动态处理器类,该类必须实现InvocationHandler接口,实现invoke方法;

 2、创建被代理的类和接口;

 3、通过Proxy类的静态方法newProxyInstance(ClassLoader loader,Class<?>[]interfaces,InvocationHandler h )方法                  创建代理对象;

4、通过代理对象调用方法。

/**
 * @Description: 测试动态代理
 */
public class JdkProxy {

    @Test
    public void test(){
        //真实类的类加载器
        ClassLoader classLoader = ProxyClass.class.getClassLoader();
        //真实类实现的所有接口数组
        Class<?>[] interfaces = ProxyClass.class.getInterfaces();
        //自己编写的动态处理器
        ProxyInvocationHandler handler = new ProxyInvocationHandler(new ProxyClass());
        /*
             newProxyInstance方法参数:
                ClassLoader loader:真实类的类加载器
                Class<?>[] interfaces: 真实类实现的所有接口数组
                InvocationHandler h:自己编写的动态处理器
         */
        ProxyInterface proxyInstance = (ProxyInterface)Proxy.newProxyInstance(
                classLoader, interfaces, handler);
        //动态调用方法
        proxyInstance.say(",动态加强方法");
    }
}

/**
 * @Description: 动态管理器类
 */
class ProxyInvocationHandler implements InvocationHandler {
    //维护目标接口
    private ProxyInterface proxyInterface;
    //通过构造器初始化目标接口,传入真实目标类对象
    public ProxyInvocationHandler(ProxyInterface proxyInterface) {
        this.proxyInterface = proxyInterface;
    }

    /**
     * 实现动态代理方法,参数:
     *      Object Proxy:需要代理的类对象,一般是这个类中维护的目标对象
     *      Method method:需要代理的方法
     *      Object[] args:需要代理的方法的参数数组
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("前置操作");
        System.out.println("method"+method);
        System.out.println("args"+args);
        /* 注意传参 */
        Object result = method.invoke(proxyInterface, args);
        System.out.println("后置操作");
        return result;
    }
}

/**
 * @Description: 目标接口
 */
interface ProxyInterface {
    public void say(String str);
}

/**
 * @Description: 目标类
 */
class ProxyClass implements ProxyInterface{
    public void say(String str) {
        System.out.println("我是目标"+str);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值