美文网首页JDK8
java动态代理Proxy.newProxyInstance

java动态代理Proxy.newProxyInstance

作者: NeWolf | 来源:发表于2020-08-10 15:51 被阅读0次

    动态代理(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;
    
    public interface IVehical {
        void run();
    }
    

    要扩展的类:

    package com.xhx.java;
     
    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;
     
    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;
     
    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方法。

    image

    可以打印一下:

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

    转载自:https://blog.csdn.net/u012326462/article/details/81293186

    相关文章

      网友评论

        本文标题:java动态代理Proxy.newProxyInstance

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