jdk动态代理

为什么需要代理

  • 使得类的责任更细粒度,比如中午要吃饭这个动作,吃饭这个动作比较固定,写在一个方法里,但是去一号食堂吃,还是去餐馆吃,还是去野餐这些都是变量,甚至吃之前我可能会先做一些仪式,吃完饭后是玩一会儿狼人杀,还是睡觉啥的,这些都是变量,可以保持吃饭这个动作的原有实现类不改变,新增一个代理类来实现。
  • 其实代理模式和装饰器模式非常像,个人看来本质区别是装饰模式确实一般都是对对象本身属性相关的增强,而代理模式可以是加上权限访问控制,打上日志或者也可以加强一点功能等等。

有了简单的代理,为什么还需要动态代理

  • 不用写一大堆傻傻的代理类,写一个通用实现就好了~~~

动态代理几个角色

  • 原始被代理对象, 必须实现至少一个接口,而且被代理的方法必须是从接口里重写的。
  • Proxy类,提供了几个静态方法,如最关键的newProxyInstance,动态生成的代理类的父类,持有一个InvocationHanlder实例的引用,动态生成的代理类就是通过调用invocationhanlder实例通过反射调用原始被代理对象的
  • InvocationHanlder接口,定义一个public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;方法,动态代理增强逻辑就是在该方法基础上实现
  • 自定义InvocationHanlder实现类,实现InvocationHanlder接口,在invoke方法中实现增强逻辑,可用过Method判断函数名来自定义哪些方法需要增强,也可以所有方法全部增强(当然,只针对原始被代理类实现了的接口中的定义的方法)
  • jdk动态生成的代理类(继承自Proxy类,实现了原始被代理类的所有接口,另外还实现了Object类中的equal,toString,hashcode三个标准方法),该代理类无基本无自定义逻辑,(前文讲到Proxy类持有InvocationHanlder实现类实例),所以该代理类只是委托了父类的InvocationHanlder实例去执行,本身只负责返回值类型转换,方法分派。

动态代理实现举例

按照各个角色一一对应

  • 原始被代理类

接口:

public interface BusinessInterface
{
    public void doSomething();
    public void doSomething2();
    public void doSomething3(String input);
}

实现类:

public class BusinessClass implements BusinessInterface
{
    public static final String  TAG = "BfdUtils";
    public void doSomething()
    {
        System.out.println("业务组件BusinessClass方法调用:doSomething()");
        doSomething2();// 在这里调用不会被拦截
    }
    public void doSomething2()
    {
        System.out.println("业务组件BusinessClass方法调用:doSomething()=====" + TAG);
    }
    @Override
    public void doSomething3(String input)
    {
        System.out.println(input);

    }
}
  • InvocationHanlder实现类增强原有类逻辑

注意,可以使用泛型方法。小技巧~

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

/**
 * User: leizhimin Date: 2008-3-20 23:24:10 Company:
 * LavaSoft(http://lavasoft.blog.51cto.com/) 动态代理处理器工具
 */
public class DynamicProxyHandler implements InvocationHandler
{
    private Object              business;                               // 被代理对象

    /**
     * 动态生成一个代理类对象,并绑定被代理类和代理处理器
     * 
     * @param business
     * @return 代理类对象
     */
    public  T bind(Object business)
    {
        this.business = business;
        return (T) Proxy.newProxyInstance(
                // 被代理类的ClassLoader

                business.getClass().getClassLoader(),
                // 要被代理的接口,本方法返回对象会自动声称实现了这些接口

                business.getClass().getInterfaces(),
                // 代理处理器对象

                this);
    }

    /**
     * 代理要调用的方法,并在方法调用前后调用连接器的方法.
     * 
     * @param proxy
     *            代理类对象
     * @param method
     *            被代理的接口方法
     * @param args
     *            被代理接口方法的参数
     * @return 方法调用返回的结果
     * @throws Throwable
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    {
        Object result = null;
        System.out.println("执行这个函数的人都是sb");
        result = method.invoke(business, args);
        System.out.println("执行完这个函数的人都不是sb");
        return result; // To change body of implemented methods use File |
                        // Settings | File Templates.

    }
}
  • 使用
public class Client
{
public static void main(String args[])
{
    DynamicProxyHandler handler = new DynamicProxyHandler();
    BusinessInterface business = new BusinessClass();
    BusinessInterface businessProxy = handler.bind(business);
    businessProxy.doSomething();//只有直接执行businessProxy的方法才会被拦截
    System.out.println("===========================");
    BusinessInterface2 business2 = new BusinessClass2();
    BusinessInterface2 businessProxy2 = handler.bind(business2);
    businessProxy2.doSomething();
}
}

源码浅析

  • 从Proxy.newProxyInstance开始
public class Proxy implements java.io.Serializable {

    private static final long serialVersionUID = -2222568056686623797L;
    
    // 生成的动态代理类在反射调用构造器实例化时需要知道构造方法的参数,前面讲过Proxy是分派方法给InvocationHandler去执行的,所有它持有一个InvocationHandler的引用。
    private static final Class[] constructorParams =
        { InvocationHandler.class };

   /* 
    * @param  type of keys
    * @param 

type of parameters * @param type of values */ // 代理类缓存 private static final WeakCache[], Class> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory()); // 持有InvocationHandler实例引用 protected InvocationHandler h; /** * Prohibits instantiation. */ private Proxy() { } // 被子类调用,protected protected Proxy(InvocationHandler h) { Objects.requireNonNull(h); this.h = h; } @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); } /* * Look up or generate the designated proxy class. */ // 黑科技魔法,动态生成一个代理类 Class cl = getProxyClass0(loader, intfs); /* * Invoke its constructor with the designated invocation handler. */ try { if (sm != null) { checkNewProxyPermission(Reflection.getCallerClass(), cl); } // 反射获取构造器(参数为InvocationHanlder那个构造器) final Constructor cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (!Modifier.isPublic(cl.getModifiers())) { AccessController.doPrivileged(new PrivilegedAction() { 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); } } private static Class getProxyClass0(ClassLoader loader, Class... interfaces) { // 限制被代理类实现的接口数65535 if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); } // 如果cache中找到了已经存在代理类,则直接返回,找不到再执行黑科技,下一节我们跳转到proxyClassCache的get方法里面去 return proxyClassCache.get(loader, interfaces); } }

  • proxyClassCache.get-生成代理类的黑科技
// 前面传进来的key为classloader, parameter为接口列表
public V get(K key, P parameter) {
        Objects.requireNonNull(parameter);

        expungeStaleEntries();

        Object cacheKey = CacheKey.valueOf(key, refQueue);

        // lazily install the 2nd level valuesMap for the particular cacheKey
        ConcurrentMap> valuesMap = map.get(cacheKey);
        if (valuesMap == null) {
            ConcurrentMap> oldValuesMap
                = map.putIfAbsent(cacheKey,
                                  valuesMap = new ConcurrentHashMap<>());
            if (oldValuesMap != null) {
                valuesMap = oldValuesMap;
            }
        }

        // create subKey and retrieve the possible Supplier stored by that
        // subKey from valuesMap
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        Supplier supplier = valuesMap.get(subKey);
        Factory factory = null;

        while (true) {
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue instance
                // 这里是关键,这里的循环是为了应对没有缓存过,或者或存了但是是个null值,或者缓存没有成功各种场景,jdk里无数个类似这样的处理逻辑,并发包里的cas基本都是这样实现的。  (如果已经缓存过了这里应该是CacheValue,没有缓存过都是Factory)
                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
            if (factory == null) {
                // 这里的factory即为第一行判断的supplier,所以进入Factory的get逻辑
                factory = new Factory(key, parameter, subKey, valuesMap);
            }

            if (supplier == null) {
                supplier = valuesMap.putIfAbsent(subKey, factory);
                if (supplier == null) {
                    // successfully installed Factory
                    // 可以看到supplier就是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);
                }
            }
        }
    }
  • WeakCache内部类Factory的get逻辑
private final class Factory implements Supplier {

        private final K key;
        private final P parameter;
        private final Object subKey;
        private final ConcurrentMap> valuesMap;

        Factory(K key, P parameter, Object subKey,
                ConcurrentMap> valuesMap) {
            this.key = key;
            this.parameter = parameter;
            this.subKey = subKey;
            this.valuesMap = valuesMap;
        }

        @Override
        public synchronized V get() { // serialize access
            // re-check
            Supplier supplier = valuesMap.get(subKey);
            if (supplier != this) {
                // 这里出现诡异的情况直接返回null,因为上层调用者的到null结果时,会继续循环,参照上面那一段代码
                return null;
            }
            // else still us (supplier == this)

            // create new value
            V value = null;
            try {
                // 这里是黑科技的真正入口, 调用了valueFactory这个bifcuntion,从Poxy类实例化WeakCcahe实例的代码可知,valueFactory为Proxy类的内部类ProxyClassFactory,下面进入Proxy内部类ProxyClassFactory
                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 cacheValue = new CacheValue<>(value);

            // try replacing us with CacheValue (this should always succeed)
            if (valuesMap.replace(subKey, this, cacheValue)) {
                // put also in reverseMap
                reverseMap.put(cacheValue, Boolean.TRUE);
            } else {
                throw new AssertionError("Should not reach here");
            }

            // successfully replaced us with new CacheValue -> return the value
            // wrapped by it
            return value;
        }
    }
  • Proxy内部类ProxyClassFactory-生成动态代理类的关键处

这里有用到IdentityHashMap(纯粹以内存地址比较key),他和hashmap的区别:
1.两者最主要的区别是IdentityHashMap使用的是==比较key的值,而HashMap使用的是equals()
2.HashMap使用的是hashCode()查找位置,IdentityHashMap使用的是System.identityHashCode(object),这里顺便提一下System.identityHashCode与Object.hashcode()的区别,前者是根据对象在内存中的地址算出来的一个数值,如果不复写hashcode方法(即实现类不自定义,沿用Object类的)两者返回值将一模一样,重写了hashcode就不一样了。
3.IdentityHashMap理论上来说速度要比HashMap快一点

private static final class ProxyClassFactory
        implements BiFunction[], Class>
    {
        // prefix for all proxy class names
        // 可见代理类类名前缀都是$Proxy
        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) {
            // 这里用IdentityHashMap
            Map, 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
            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.
             */
            // 决定生成的代理类放到哪个包下面,如果接口里有非公开接口(java的接口只有public和包级别两个访问级别),则与接口的包一致(前提是所有的包级别接口需要在同一个包下面),如果全部都是pubic的接口,则放到 com.sun.proxy包下面。
            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();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * Generate the specified proxy class.
             */
            // 这里生成了代理类的二进制类文件, ProxyGenerator.generateProxyClass,在sun.misc包里面,没法看里面的代码。
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {
                // 加载这个类
                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.generateProxyClass源码没法看了,所以把这里生成的类文件提取出来。看看动态代理类长什么样子

tips:懒得去手动弄这个类文件了,网上拷贝的,所以实现的接口不是上面的例子中的~~~~~~~~~呵呵

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import proxy.sample.IBye;

// 和源码一样,以$Proxy作为代理类名前缀,跟上数字0,说明这是第一个生成的代理类~,继承自Proxy类,实现了被代理类实现的每一个接口
public final class $Proxy0 extends Proxy implements IBye {
    private static Method m1;
    private static Method m3;
    private static Method m0;
    private static Method m2;

    public $Proxy0(InvocationHandler var1) throws  {
        // 构造器一定会调用父类构造器,注入InvocationHandler实例
        super(var1);
    }

    // equals,toString,hashcode几个方法每个代理类都会有。 
    public final boolean equals(Object var1) throws  {
        try {
            return ((Boolean)super.h.invoke(this, m1, new Object[]{var1})).booleanValue();
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    // 生成的接口方法的实现,委托父类的InvocationHandler实例去执行,执行的方法是m3,这里返回是void,所以没有结果类型转换逻辑。
    public final void bye() throws  {
        try {
            super.h.invoke(this, m3, (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)).intValue();
        } 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);
        }
    }

   // 需要分派的Method用静态类构造器在类初始化时注入。
    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[]{Class.forName("java.lang.Object")});
            m3 = Class.forName("proxy.sample.IBye").getMethod("bye", new Class[0]);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

总结

就一句话,jdk动态代理是针对接口实现的!!!!!
jdk动态代理是针对接口实现的!!!!!
jdk动态代理是针对接口实现的!!!!!

所以这句话看起来有很大的歧义----jdk动态代理的类必须实现了接口(这个类如果确实实现了接口,但是他有自己定义的一些public的不是接口中定义的方法怎么办?显然没发代理的~)

奥,还有,多个接口定义同一个方法,动态代理类只认一个,只认一个,只认一个!

你可能感兴趣的:(jdk动态代理)