Java的动态代理Proxy.newProxyInstance

本文参考:java动态代理Proxy.newProxyInstance-CSDN博客

一、动态代理定义

利用Java的反射技术,在运行期间创建可以实现某些给定接口的新类,称为动态代理类。

此处代理的接口(Interfaces),不是类(Class)。

动态代理是因为在运行时才知道具体的类的实现(接口对应不同的实现,动态调用)。

二、动态代理JDK的实现方法

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

newProxyInstance方法有三个参数:

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

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

(3)InvocationHandler:动态代理方法在执行时,会调用此处的invoke方法去执行

invoke的原型:

new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    }
}

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

2)method:调用的方法,此处为被代理对象的方法

3)args:方法中的参数,此处为被代理对象的方法的参数

invoke会根据被代理对象的方法个数被执行多次。

三、示例

(1)定义接口

public interface IVehical {

    void run();

    void show();
}

(2)实现接口

public class Car implements IVehical {
    @Override
    public void run() {
        System.out.println("Car会跑");
    }

    @Override
    public void show() {
        System.out.println("Car show...");
    }
}

(3)动态代理

public class ProxyTest {

    public static void main(String[] args) {
        IVehical car = new Car();

        Object beanProxy = Proxy.newProxyInstance(
                car.getClass().getClassLoader(),
                car.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if(method.getName().equals("run")){
                            System.out.println("---------before---------");
                            Object result = method.invoke(car, args);
                            System.out.println("---------after---------");
                            return result;
                        }else{
                            Object result = method.invoke(car, args);
                            return result;
                        }

                    }
                }
        );

        ((IVehical)beanProxy).run();
        ((IVehical)beanProxy).show();
    }
}

(4)执行结果

---------before---------
Car会跑
---------after---------
Car show...
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值