JDK动态代理之源码分析

一、代理模式是什么?

代理模式就是给一个对象提供一个代理对象,并由代理对象管理着被代理对象的引用。就像生活中的代理律师,你只需要找好代理律师,剩下的都交给代理律师来打理。

Spring MVC 有两大特性,IoC 和 AOP。IoC为控制反转,这里不做介绍;AOP(Aspect Oriented Programming   面向切面编程)的实现就是基于代理技术。

 

二、静态代理

先来看下什么是静态代理。静态代理在程序运行前,就已经编写好代理类,实现静态代理需要以下:

  1、定义业务接口

  2、被代理对象实现业务接口

  3、代理对象实现业务接口并持有被代理对象的引用

码上看

2.1 业务接口

package cn.zjm.show.proxy;

/**
 * @author Zhao JinMing
 * @date 2018年9月14日 09:49
 */

public interface IUserService {

    void add(String name);
}

2.2 被代理对象实现接口

package cn.zjm.show.proxy;

/**
 * @author Zhao JinMing
 * @date 2018年9月14日 09:49
 */
public class UserServiceImpl implements IUserService {

    @Override
    public void add(String name) {
        System.out.println("添加用户“" + name + "”成功。");
    }
}

2.3 代理对象实现接口并持有代理对象引用

package cn.zjm.show.proxy;

/**
 * @author Zhao JinMing
 * @date 2018年9月14日 09:50
 */
public class UserServiceProxy implements IUserService {

    private IUserService proxy;

    public UserServiceProxy(IUserService proxy) {
        this.proxy = proxy;
    }

    @Override
    public void add(String name) {
        System.out.println("开始插入");
        proxy.add(name);
        System.out.println("结束插入");
    }
}

2.4 代码测试

package cn.zjm.show.proxy;

public class SourceProxy {

    public static void main(String[] args) {
        IUserService userService = new UserServiceImpl();
        IUserService proxy = new UserServiceProxy(userService);

        proxy.add("王五");
    }
}

2.5 输出结果

开始插入
添加用户“王五”成功。
结束插入

2.6 总结

既然已经有动态代理了,那为什么还需要动态代理。毋庸置疑肯定是静态代理与动态代理相比有着很多的缺陷。从扩展性的角度考虑,如果业务接口添加或者删除方法,那么不仅仅是被代理类需要修改,代理类也需要修改。而且对于不同的业务接口,需要写不同的代理类,这么麻烦的操作,怕麻烦的大佬肯定受不了,于是乎动态代理来了。

 

三、动态代理

所谓的动态代理,就是在程序运行的时候,根据需要动态的创建代理类及其实例来完成具体的操作。动态代理又分为JDK动态代理和cglib动态代理两大类,下面介绍的是JDK动态代理。

3.1 使用JDK动态代理的步骤

①定义业务接口

②被代理对象实现业务接口

③通过Proxy的静态方法newProxyInstance( ClassLoaderloader, Class[] interfaces, InvocationHandler h)创建一个代理对象

④使用代理对象

3.1 定义业务接口

package cn.zjm.show.proxy;

/**
 * @author Zhao JinMing
 * @date 2018年9月14日 09:49
 */
public interface IUserService {

    void add(String name);
}

3.2 被代理对象实现业务接口

package cn.zjm.show.proxy;

/**
 * @author Zhao JinMing
 * @date 2018年9月14日 09:49
 */
public class UserServiceImpl implements IUserService {

    @Override
    public void add(String name) {
        System.out.println("添加用户“" + name + "”成功。");
    }
}

3.3 创建代理对象并使用

package cn.zjm.show.proxy;

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

public class SourceProxy {

    public static void main(String[] args) {
        IUserService userService = new UserServiceImpl();
        IUserService proxy = (IUserService) Proxy.newProxyInstance(SourceProxy.class.getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("准备使用动态代理插入数据");
                Object invoke = method.invoke(userService, args);
                System.out.println("使用动态代理插入对象结束");
                return invoke;
            }
        });
        proxy.add("王五");
    }
}

3.4 运行结果

准备使用动态代理插入数据
添加用户“王五”成功。
使用动态代理插入对象结束

运行结果和静态代理一样,说明成功了。但是,我们注意到,我们并没有像静态代理那样去自己定义一个代理类,并实例化代理对象。实际上,动态代理的代理对象是在内存中的,是JDK根据我们传入的参数生成好的。那动态代理的代理类和代理对象是怎么产生的呢?

四、源码分析

首先来看 newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)

    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        //判断h是否为空
        Objects.requireNonNull(h);
        //对接口数组的拷贝
        final Class<?>[] intfs = interfaces.clone();
        //安全检查
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         * Look up or generate the designated proxy class.
         * 查询(在缓存中已经有)或生成指定的代理类的class对象。
         *     --核心代码
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         * 用invocationHandler生成构造函数
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }
            //得到代理对象的构造函数
            //private static final Class<?>[] constructorParams ={ InvocationHandler.class };
            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});
        } 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(loader, intfs)得到代理类的Class对象,然后通过Class对象获得构造方法,进而创建代理对象。再看getProxyClass0(loader, intfs)方法。

getProxyClass0(loader, intfs)

    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        //接口数量不能大于65535
        if (interfaces.length > 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
        /*
            如果由实现给定接口的给定加载器定义的代理类存在,则这将简单地返回缓存的副本;
            否则,它将通过ProxyClassFactory创建代理类
        */
        return proxyClassCache.get(loader, interfaces);
    }


    // private static final WeakCache<ClassLoader, Class<?>[], Class<?>> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

    // proxyClassCache是WeakCache类的实例,WeakCache又是什么?

再看看 WeakCache 是什么

//K为key类型,P为参数类型,V为value类型
//根据传进来的参数,K为ClassLoader类型,P为Class<?>[]类型,V为Class<?>类型
final class WeakCache<K, P, V> {

    private final ReferenceQueue<K> refQueue
        = new ReferenceQueue<>();
    // the key type is Object for supporting null key
    private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map
        = new ConcurrentHashMap<>();
    private final ConcurrentMap<Supplier<V>, Boolean> reverseMap
        = new ConcurrentHashMap<>();
    private final BiFunction<K, P, ?> subKeyFactory;
    private final BiFunction<K, P, V> valueFactory;


    public WeakCache(BiFunction<K, P, ?> subKeyFactory,
                     BiFunction<K, P, V> valueFactory) {
        this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
        this.valueFactory = Objects.requireNonNull(valueFactory);
    }

map变量为实现缓存的核心变量,他是一个双重map结构(key,sub-key。

在进入proxyClassCache.get(loader, interfaces)

    public V get(K key, P parameter) {
        //检查参数是否为空
        Objects.requireNonNull(parameter);
        //清除无效的缓存
        expungeStaleEntries();
        //cacheKey 为上述map中的一级key
        Object cacheKey = CacheKey.valueOf(key, refQueue);

        // lazily install the 2nd level valuesMap for the particular cacheKey
        //根据一级key得到ConcurrentMap<Object, Supplier<V>>对象,如果不存在,如果不存在就新建一个ConcurrentMap<Object, Supplier<V>>对象
        ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
        if (valuesMap == null) {
            ConcurrentMap<Object, Supplier<V>> oldValuesMap
                = map.putIfAbsent(cacheKey,
                                  valuesMap = new ConcurrentHashMap<>());
            if (oldValuesMap != null) {
                valuesMap = oldValuesMap;
            }
        }

        // create subKey and retrieve the possible Supplier<V> stored by that
        // subKey from valuesMap
        // 创建sub-key、获取存储的Supplier<V>
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        // 通过sub-key得到supplier
        Supplier<V> supplier = valuesMap.get(subKey);
        Factory factory = null;

        while (true) {
            //如果缓存中有supplier,就直接通过get方法得到代理对象返回
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance
                V value = supplier.get();
                if (value != null) {
                    return value;
                }
            }
            // else no supplier in cache
            // or a supplier that returned null (could be a cleared CacheValue
            // or a Factory that wasn't successful in installing the CacheValue)

            // lazily construct a Factory
            //面的所有代码目的就是:如果缓存中没有supplier,则创建一个Factory对象,把factory对象在多线程的环境下安全的赋给supplier。
            if (factory == null) {
                factory = new Factory(key, parameter, subKey, valuesMap);
            }

            if (supplier == null) {
                supplier = valuesMap.putIfAbsent(subKey, factory);
                if (supplier == null) {
                    // successfully installed Factory
                    supplier = factory;
                }
                // else retry with winning supplier
            } else {
                if (valuesMap.replace(subKey, supplier, factory)) {
                    // successfully replaced
                    // cleared CacheEntry / unsuccessful Factory
                    // with our Factory
                    supplier = factory;
                } else {
                    // retry with current supplier
                    supplier = valuesMap.get(subKey);
                }
            }
        }
    }

再来看Factory中的 get() 方法

public synchronized V get() { // serialize access
    // re-check
    Supplier<V> supplier = valuesMap.get(subKey);
    //检查得到的supplier是不是当前对象
    if (supplier != this) {
        // something changed while we were waiting:
        // might be that we were replaced by a CacheValue
        // or were removed because of failure ->
        // return null to signal WeakCache.get() to retry
        // the loop
        return null;
    }
    // else still us (supplier == this)

    // create new value
    V value = null;
    try {
        //代理类在这里得到代理对象
        //重点方法valueFactory.apply(key, parameter)
        value = Objects.requireNonNull(valueFactory.apply(key, parameter));
    } finally {
        if (value == null) { // remove us on failure
            valuesMap.remove(subKey, this);
        }
    }
    // the only path to reach here is with non-null value
    assert value != null;

    // wrap value with CacheValue (WeakReference)
    CacheValue<V> cacheValue = new CacheValue<>(value);

    // put into reverseMap
    reverseMap.put(cacheValue, Boolean.TRUE);

    // try replacing us with CacheValue (this should always succeed)
    if (!valuesMap.replace(subKey, this, cacheValue)) {
        throw new AssertionError("Should not reach here");
    }

    // successfully replaced us with new CacheValue -> return the value
    // wrapped by it
    return value;
}

再看 ProxyClassFactory 的 apply() 方法

//这里的BiFunction<T, U, R>是个函数式接口,可以理解为用T,U两种类型做参数,得到R类型的返回值
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) {
             
           Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
           //验证代理接口,可不看
           for (Class<?> intf : interfaces) {
               /*
                * Verify that the class loader resolves the name of this
                * interface to the same Class object.
                */
               Class<?> interfaceClass = null;
               try {
                   interfaceClass = Class.forName(intf.getName(), false, loader);
               } catch (ClassNotFoundException e) {
               }
               if (interfaceClass != intf) {
                   throw new IllegalArgumentException(
                       intf + " is not visible from class loader");
               }
               /*
                * Verify that the Class object actually represents an
                * interface.
                */
               if (!interfaceClass.isInterface()) {
                   throw new IllegalArgumentException(
                       interfaceClass.getName() + " is not an interface");
               }
               /*
                * Verify that this interface is not a duplicate.
                */
               if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                   throw new IllegalArgumentException(
                       "repeated interface: " + interfaceClass.getName());
               }
           }
           //生成的代理类的包名 
           String proxyPkg = null;     // package to define proxy class in
           //代理类访问控制符: public ,final
           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.
            */
           //验证所有非公共的接口在同一个包内;公共的就无需处理
           //生成包名和类名的逻辑,包名默认是com.sun.proxy,类名默认是$Proxy 加上一个自增的整数值
           //如果被代理类是 non-public proxy interface ,则用和被代理类接口一样的包名
           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
               proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
           }

           /*
            * Choose a name for the proxy class to generate.
            */
           long num = nextUniqueNumber.getAndIncrement();
           //代理类的完全限定名,如com.sun.proxy.$Proxy0.calss
           String proxyName = proxyPkg + proxyClassNamePrefix + num;

           /*
            * Generate the specified proxy class.
            */
           //核心部分,生成代理类的字节码
           byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
               proxyName, interfaces, accessFlags);
           try {
               //把代理类加载到JVM中,至此动态代理过程基本结束了
               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());
           }
       }
   }

获取字节码文件

package cn.zjm.show.proxy;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class SourceProxy {

    public static void main(String[] args) {
        IUserService userService = new UserServiceImpl();
        IUserService proxy = (IUserService) Proxy.newProxyInstance(SourceProxy.class.getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("动态代理开始");
                Object invoke = method.invoke(userService, args);
                System.out.println("动态代理结束");
                return invoke;
            }
        });

        proxy.add("王五");

        String path = "D:/$Proxy0.class";
        byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", userService.getClass().getInterfaces());
        FileOutputStream out = null;

        try {
            out = new FileOutputStream(path);
            out.write(classFile);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

反编译后

import cn.zjm.show.proxy.IUserService;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0
  extends Proxy
  implements IUserService
{
  private static Method m1;
  private static Method m2;
  private static Method m4;
  private static Method m3;
  private static Method m0;
  
  public $Proxy0(InvocationHandler paramInvocationHandler)
    throws 
  {
    super(paramInvocationHandler);
  }
  
  public final boolean equals(Object paramObject)
    throws 
  {
    try
    {
      return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  public final String toString()
    throws 
  {
    try
    {
      return (String)this.h.invoke(this, m2, null);
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  public final void del(String paramString)
    throws 
  {
    try
    {
      this.h.invoke(this, m4, new Object[] { paramString });
      return;
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  public final void add(String paramString)
    throws 
  {
    try
    {
      this.h.invoke(this, m3, new Object[] { paramString });
      return;
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  public final int hashCode()
    throws 
  {
    try
    {
      return ((Integer)this.h.invoke(this, m0, null)).intValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  static
  {
    try
    {
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
      m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
      m4 = Class.forName("cn.zjm.show.proxy.IUserService").getMethod("del", new Class[] { Class.forName("java.lang.String") });
      m3 = Class.forName("cn.zjm.show.proxy.IUserService").getMethod("add", new Class[] { Class.forName("java.lang.String") });
      m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
      return;
    }
    catch (NoSuchMethodException localNoSuchMethodException)
    {
      throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
    }
    catch (ClassNotFoundException localClassNotFoundException)
    {
      throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
    }
  }
}

猜你喜欢

转载自blog.csdn.net/u010960184/article/details/82697629