java动态代理

来源:互联网 发布:淘宝认证手势照 编辑:程序博客网 时间:2024/05/29 14:15

jdk动态代理

  • 目标接口和实现类
public interface UserService {    void save();}public class UserServiceImpl implements UserService {    @Override    public void save() {        System.out.println("save user");    }}
  • 代理类
public class ProxyInvocation implements InvocationHandler {    private Object target;    public UserService getProxy() {        return (UserService) Proxy.newProxyInstance(Thread.currentThread()                        .getContextClassLoader(), target.getClass().getInterfaces(),                this);    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println("before invoke");        Object object = method.invoke(target, args);        System.out.println("after invoke");        return object;    }    public ProxyInvocation() {    }    public ProxyInvocation(Object target) {        this.target = target;    }}
  • 测试
  @org.junit.Test    public void test(){        UserService userService = new UserServiceImpl();        ProxyInvocation proxyInvocation = new ProxyInvocation(userService);        proxyInvocation.getProxy().save();    }
  • 测试结果

    before invoke
    save user
    after invoke

  • 过程分析

    1. 进入newProxyInstance方法
    2. 进入Class<?> cl = getProxyClass0(loader, intfs)
    3. 进入proxyClassCache.get(loader, interfaces)
    4. 看到这里Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter))查看apply代码,就可以看到反射生成class对象了.
@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);        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});        } 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) {        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        //优先从缓存获取class        return proxyClassCache.get(loader, interfaces);    }
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<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        //如果不存在则新建        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));        Supplier<V> supplier = valuesMap.get(subKey);        Factory factory = null;        while (true) {            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            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);                }            }        }    }
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 {                   //终于看到熟悉的反射创建class对象                    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.             */            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.             */            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());            }        }    }

cglib代理

  • 目标接口和实现类
public interface UserService {    void save();}public class UserServiceImpl implements UserService {    @Override    public void save() {        System.out.println("save user");    }}
  • 代理类
public class ProxyCglib implements MethodInterceptor{    @Override    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {        System.out.println("before");        methodProxy.invokeSuper(o, objects);        System.out.println("after");        return null;    }}
  • 测试
@org.junit.Test    public void test(){        ProxyCglib proxyCglib = new ProxyCglib();        Enhancer enhancer = new Enhancer();        enhancer.setSuperclass(UserServiceImpl.class);        enhancer.setCallback(proxyCglib);        UserService userService= (UserService) enhancer.create();        userService.save();    }

这里只是简单地展示了cglib的用法,实际上cglib能做的远远不止如此,待看springaop源码的时候再来深究.

  • 测试结果
    before
    save user
    after

两者的不同点

  • JDK动态代理只能对实现了接口的类生成代理,而不能针对类
  • CGLIB是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法
  • 因为是继承,所以该类或方法最好不要声明成final
  • 在使用spring来管理事物的时候,如果采用jdk动态代理的话注解可以加在接口或者实现类上面,采用cglib动态代理的话只能加在实现类上面.

最后是关于动态代理一些博客推荐

  • Spring AOP 实现原理与 CGLIB 应用
  • 深入浅出 cglib,打造无入侵的类代理
  • JDK动态代理实现原理
  • CGlib使用笔记
  • Java动态代理机制详解(JDK 和CGLIB,Javassist,ASM)

有问题或建议请联系邮箱:981017952@qq.com,qq:981017952

0 0
原创粉丝点击