码迷,mamicode.com
首页 > 其他好文 > 详细

代理模式(静态代理,JDK动态代理,JDK动态代理原理分析)

时间:2020-06-14 23:25:57      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:==   代理   man   ack   ted   function   查看   cat   dex   

代理模式

静态代理

代理类和被代理类在编译期间就已经确定了。

package org.westos.demo4;

/**
 * @author lwj
 * @date 2020/6/14 15:42
 */
public interface UserDao {
    void add();

    void delete();

    void update();

    void query();
}
package org.westos.demo4;

/**
 * @author lwj
 * @date 2020/6/14 15:42
 */
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("添加一个用户");
    }

    @Override
    public void delete() {
        System.out.println("删除一个用户");
    }

    @Override
    public void update() {
        System.out.println("更新用户信息");
    }

    @Override
    public void query() {
        System.out.println("查询用户信息");
    }
}

静态代理类

package org.westos.demo4;

/**
 * @author lwj
 * @date 2020/6/14 15:43
 */
public class UserDaoStaticProxy implements UserDao {
    private UserDao userDao;

    public UserDaoStaticProxy(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void add() {
        System.out.println("权限校验");
        userDao.add();
        System.out.println("输出日志");
    }

    @Override
    public void delete() {
        System.out.println("权限校验");
        userDao.delete();
        System.out.println("输出日志");
    }

    @Override
    public void update() {
        System.out.println("权限校验");
        userDao.update();
        System.out.println("输出日志");
    }

    @Override
    public void query() {
        System.out.println("权限校验");
        userDao.query();
        System.out.println("输出日志");
    }
}

测试类

package org.westos.demo4;

/**
 * @author lwj
 * @date 2020/6/14 15:45
 */
public class MyTest {
    public static void main(String[] args) {
        UserDaoImpl impl = new UserDaoImpl();
        UserDaoStaticProxy userDaoStaticProxy = new UserDaoStaticProxy(impl);
        userDaoStaticProxy.add();
        //权限校验
        //添加一个用户
        //输出日志
    }
}

动态代理

package org.westos.demo5;

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

/**
 * @author lwj
 * @date 2020/6/14 15:53
 */
public class ProxyFactory {
    public static Object getProxyInstance(Object obj) {
        //obj被代理对象

        /*
        加载代理类,和被代理类的类加载器一致
        被代理类所实现的接口
        InvocationHandler:
         */
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //需要我们自己编写的增强的代码
                        //proxy:代理对象  Method:被代理类的方法对象  args:被代理类的方法需要的参数
                        System.out.println("权限校验");
                        Object invoke = method.invoke(obj, args);
                        //调用被代理类的方法执行
                        System.out.println("输出日志");
                        return invoke;
                    }
                });
    }
}

测试类

package org.westos.demo5;

import org.westos.demo4.UserDao;
import org.westos.demo4.UserDaoImpl;

/**
 * @author lwj
 * @date 2020/6/14 16:10
 */
public class MyTest {
    public static void main(String[] args) {
        UserDaoImpl impl = new UserDaoImpl();
        UserDao proxyInstance = (UserDao) ProxyFactory.getProxyInstance(impl);
        System.out.println(proxyInstance.getClass());
        //class com.sun.proxy.$Proxy0
        proxyInstance.add();
        //权限校验
        //添加一个用户
        //输出日志
    }
}

或者

package org.westos.proxy;

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

/**
 * @author lwj
 * @date 2020/6/14 17:51
 */
public class ProxyFactory {
    public static Object getProxyInstance(Object obj) {
        //obj 被代理对象
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler(obj);
        /*
        代理类实现被代理类实现的接口
        用被代理类的类加载器加载代理类
         */
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                myInvocationHandler);
    }
}

class MyInvocationHandler implements InvocationHandler {
    private Object obj;
    //被代理对象

    public MyInvocationHandler(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("权限校验");
        Object invoke = method.invoke(obj, args);
        System.out.println("输出日志");
        return invoke;
    }
}

测试类

package org.westos.proxy;

/**
 * @author lwj
 * @date 2020/6/14 17:52
 */
public class MyTest {
    public static void main(String[] args) {
        UserDaoImpl impl = new UserDaoImpl();
        UserDao proxyInstance = (UserDao) ProxyFactory.getProxyInstance(impl);
        System.out.println(proxyInstance.getClass());
        //class com.sun.proxy.$Proxy0
        proxyInstance.add();
    }
}

上述两种方式都可以。

动态代理原理分析

对于接口来说,使用JDK的动态代理来实现,就是上面的两种方式,而对于类的代理,使用CGLIB来实现。

JDK的动态代理,就是在程序运行的过程中,根据被代理的接口来动态生成代理类的class文件,并加载运行的过程。

JDK提供了java.lang.reflect.Proxy类来实现动态代理,可通过它的newProxyInstance()方法来获得代理实现类对象,同时对于代理的接口的实际处理,是一个java.lang.reflect.InvocationHandler,它提供了invoke()方法供实现者提供相应的代理逻辑,可以对实际的实现进行特殊处理。

首先来看newProxyInstance()方法,

@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
                                      Class<?>[] interfaces,
                                      InvocationHandler h)
    throws IllegalArgumentException
    {
        Objects.requireNonNull(h);

        final Class<?>[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        Class<?> cl = getProxyClass0(loader, intfs);
        //真正生成代理类class对象的地方

        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            return cons.newInstance(new Object[]{h});
            //将自定义的InvocationHandler对象作为代理类的构造方法的参数,创建代理类的实例对象
        } catch (IllegalAccessException|InstantiationException e) {
            throw new InternalError(e.toString(), e);
        } catch (InvocationTargetException e) {
            Throwable t = e.getCause();
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new InternalError(t.toString(), t);
            }
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString(), e);
        }
    }

重点关注getProxyClass0()方法,

private static Class<?> getProxyClass0(ClassLoader loader,
                                       Class<?>... interfaces) {
    if (interfaces.length > 65535) {
        //代理的接口数量不能大于65535
        throw new IllegalArgumentException("interface limit exceeded");
    }

    // If the proxy class defined by the given loader implementing
    // the given interfaces exists, this will simply return the cached copy;
    // otherwise, it will create the proxy class via the ProxyClassFactory
    
    //JDK对代理进行了缓存,如果已经存在相应的代理类,则直接返回,否则才会通过ProxyClassFactory来创建代理
    return proxyClassCache.get(loader, interfaces);
}

这里关心ProxyClassFactory是如何生成代理类的,ProxyClassFactory是Proxy的一个静态内部类,

private static final class ProxyClassFactory
    implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names 所有代理类的前缀
        private static final String proxyClassNamePrefix = "$Proxy";

        // next number to use for generation of unique proxy class names
        // 用于生成代理类名字的计数器
        private static final AtomicLong nextUniqueNumber = new AtomicLong();

        @Override
        public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

            //...省略验证接口的代码

            String proxyPkg = null;     // package to define proxy class in
            //生成的代理类的包名
            int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

            /*
             * Record the package of a non-public proxy interface so that the
             * proxy class will be defined in the same package.  Verify that
             * all non-public proxy interfaces are in the same package.
             */
             //对于非公共接口,代理类的包名和接口的包名相同
            for (Class<?> intf : interfaces) {
                int flags = intf.getModifiers();
                if (!Modifier.isPublic(flags)) {
                    accessFlags = Modifier.FINAL;
                    String name = intf.getName();
                    int n = name.lastIndexOf(‘.‘);
                    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                    if (proxyPkg == null) {
                        proxyPkg = pkg;
                    } else if (!pkg.equals(proxyPkg)) {
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }
			
            if (proxyPkg == null) {
                // if no non-public proxy interfaces, use com.sun.proxy package
                // 公共接口的包名,默认为com.sum.proxy.
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * Choose a name for the proxy class to generate.
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;
			//默认情况下,代理类的完全限定名为:com.sun.proxy.$Proxy0,com.sun.proxy.$Proxy1……依次递增
			
            /*
             * Generate the specified proxy class.
             * 生成代理类的字节码文件
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
                
            try {
            	//根据二进制字节码返回相应的Class实例
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length);
            } catch (ClassFormatError e) {
                /*
                 * A ClassFormatError here means that (barring bugs in the
                 * proxy class generation code) there was some other
                 * invalid aspect of the arguments supplied to the proxy
                 * class creation (such as virtual machine limitations
                 * exceeded).
                 */
                throw new IllegalArgumentException(e.toString());
            }
        }
    }

ProxyGenerator类是sun.misc包中的类,

public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
    ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
    final byte[] var4 = var3.generateClassFile();
    if (saveGeneratedFiles) {
        //根据此boolean类型参数决定是否把生成的字节码保存在本地磁盘
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                try {
                    int var1 = var0.lastIndexOf(46);
                    Path var2;
                    if (var1 > 0) {
                        Path var3 = Paths.get(var0.substring(0, var1).replace(‘.‘, File.separatorChar));
                        Files.createDirectories(var3);
                        var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
                    } else {
                        var2 = Paths.get(var0 + ".class");
                    }

                    Files.write(var2, var4, new OpenOption[0]);
                    return null;
                } catch (IOException var4x) {
                    throw new InternalError("I/O exception saving generated file: " + var4x);
                }
            }
        });
    }

    return var4;
}

那么这个参数为:

private static final boolean saveGeneratedFiles = (Boolean)AccessController.doPrivileged(new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles"));

GetBooleanAction实际上是调用Boolean.getBoolean(propName)来获得的,

return Boolean.getBoolean(this.theProp)

Boolean.getBoolean(propName)调用了System.getProperty(name),

public static boolean getBoolean(String name) {
    boolean result = false;
    try {
        result = parseBoolean(System.getProperty(name));
    } catch (IllegalArgumentException | NullPointerException e) {
    }
    return result;
}

所以我们可以设置

sun.misc.ProxyGenerator.saveGeneratedFiles这个系统属性为true来把生成的class保存到本地文件来查看。

在之前的测试类中增加一条代码,设置系统属性,

package org.westos.demo5;

import org.westos.demo4.UserDao;
import org.westos.demo4.UserDaoImpl;

/**
 * @author lwj
 * @date 2020/6/14 16:10
 */
public class MyTest {
    public static void main(String[] args) {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        UserDaoImpl impl = new UserDaoImpl();
        UserDao proxyInstance = (UserDao) ProxyFactory.getProxyInstance(impl);
        System.out.println(proxyInstance.getClass());
        //class com.sun.proxy.$Proxy0
        proxyInstance.add();
        //权限校验
        //添加一个用户
        //输出日志
    }
}

该代理类的class字节码文件保存在com.sun.proxy目录下,

package com.sun.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import org.westos.demo4.UserDao;

public final class $Proxy0 extends Proxy implements UserDao {
    private static Method m1;
    private static Method m6;
    private static Method m2;
    private static Method m3;
    private static Method m5;
    private static Method m0;
    private static Method m4;

    public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void query() throws  {
        try {
            super.h.invoke(this, m6, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void add() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void delete() throws  {
        try {
            super.h.invoke(this, m5, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void update() throws  {
        try {
            super.h.invoke(this, m4, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m6 = Class.forName("org.westos.demo4.UserDao").getMethod("query");
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m3 = Class.forName("org.westos.demo4.UserDao").getMethod("add");
            m5 = Class.forName("org.westos.demo4.UserDao").getMethod("delete");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
            m4 = Class.forName("org.westos.demo4.UserDao").getMethod("update");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

JDK的动态代理类:

  • 继承了Proxy类,实现了接口,正是由于Java不支持多继承,所以动态代理类已经继承了Proxy类,则不能则继承其他类,所以JDK的动态代理只能代理接口,而不能代理类;
  • 提供了一个InvocationHandler类型参数的构造方法;
  • 提供静态代码块来初始化接口中方法的Method对象;
  • 可以看到在代理类实现接口的方法中,都调用了InvocationHandler对象的invoke()方法,所以在执行接口中的方法时,都会执行InvocationHandler的invoke()方法。

代理模式(静态代理,JDK动态代理,JDK动态代理原理分析)

标签:==   代理   man   ack   ted   function   查看   cat   dex   

原文地址:https://www.cnblogs.com/shawnyue-08/p/13127500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!