JDK1.8 Proxy

Proxy 1.8

以下源码分析取核心代码

变量定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/** parameter types of a proxy class constructor */
private static final Class<?>[] constructorParams =
{ InvocationHandler.class };

/**
* a cache of proxy classes
*/
// #1
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

/**
* the invocation handler for this proxy instance.
* @serial
*/
protected InvocationHandler h;
  1. 根据注释很容易理解,1.8在1.7基础上优化代码,依然是弱引用做为缓存。key和value都采用工厂模式。

    KeyFactory

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
    * A function that maps an array of interfaces to an optimal key where
    * Class objects representing interfaces are weakly referenced.
    */
    private static final class KeyFactory
    implements BiFunction<ClassLoader, Class<?>[], Object>
    {
    @Override
    public Object apply(ClassLoader classLoader, Class<?>[] interfaces) {
    switch (interfaces.length) {
    case 1: return new Key1(interfaces[0]); // the most frequent
    case 2: return new Key2(interfaces[0], interfaces[1]);
    case 0: return key0;
    default: return new KeyX(interfaces);
    }
    }
    }
  2. 根据上下文代码及注释,可以知道这是工厂模式。

  3. 实现BiFunction函数,BiFunction是函数式接口。
  4. Key1Key2KeyX,代表接口数量。分别是1个接口、2个接口、多个接口。
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×