java动态代理Proxy.newProxyInstance

动态代理(dynamic proxy)

           利用Java的反射技术(Java Reflection),在运行时创建一个实现某些给定接口的新类(也称“动态代理类”)及其实例(对象),代理的是接口(Interfaces),不是类(Class),也不是抽象类。在运行时才知道具体的实现,spring aop就是此原理。

 

 

   public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException

newProxyInstance,方法有三个参数:

loader: 用哪个类加载器去加载代理对象

interfaces:动态代理类需要实现的接口

h:动态代理方法在执行时,会调用h里面的invoke方法去执行

 

 

定义一个接口:

package com.xhx.java;

/**
 * xuhaixing
 * 2018/7/30 21:32
 **/
public interface IVehical {
    void run();
}

要扩展的类:

package com.xhx.java;

/**
 * xuhaixing
 * 2018/7/30 21:33
 **/
public class Car implements IVehical {
    public void run() {
        System.out.println("Car会跑");
    }
}

调用处理类invocationhandler

package com.xhx.java;

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

/**
 * xuhaixing
 * 2018/7/30 21:38
 **/
public class VehicalInvacationHandler implements InvocationHandler {

    private final IVehical vehical;
    public VehicalInvacationHandler(IVehical vehical){
        this.vehical = vehical;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("---------before-------");
        Object invoke = method.invoke(vehical, args);
        System.out.println("---------after-------");

        return invoke;
    }
}

invoke三个参数:

proxy:就是代理对象,newProxyInstance方法的返回对象

method:调用的方法

args: 方法中的参数

 

package com.xhx.java;

import java.lang.reflect.Proxy;

/**
 * xuhaixing
 * 2018/7/30 21:30
 **/
public class App {
    public static void main(String[] args) {
        IVehical car = new Car();

        IVehical vehical = (IVehical)Proxy.newProxyInstance(car.getClass().getClassLoader(), Car.class.getInterfaces(), new VehicalInvacationHandler(car));
        vehical.run();
    }
}

上面代码中,代理car对象,调用run方法时,自动执行invocationhandler中的invoke方法。

 

可以打印一下:

 System.out.println(vehical.getClass());

 

实时内容请关注微信公众号,公众号与博客同时更新:程序员星星

  • 78
    点赞
  • 263
    收藏
    觉得还不错? 一键收藏
  • 23
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值