先抛出一个问题,JDK的动态代理为什么不支持对实现类的代理,只支持接口的代理???
首先来看一下如何使用JDK动态代理。JDK提供了Java.lang.reflect.Proxy类来实现动态代理的,可通过它的newProxyInstance来获得代理实现类。同时对于代理的接口的实际处理,是一个java.lang.reflect.InvocationHandler,它提供了一个invoke方法供实现者提供相应的代理逻辑的实现。
下面实现一个jdk动态代理的例子:
1.被代理的接口,编写一个接口HelloTest
package com.proxy.test2;
public interface HelloTest { void say(String name); }
2.HelloTestImpl 实现接口HelloTest
package com.proxy.test2;
public class HelloTestImpl implements HelloTest {
@Override
public void say(String name) {
System.out.println("Hello:"+name);
}
}
3.JDK的动态代码需要实现InvocationHandler
package com.proxy.test2;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class CustomInvocationHandler implements InvocationHandler { private Object target; public CustomInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before invocation"); Object retVal = method.invoke(target, args); System.out.println("After invocation"); return retVal; } }
4.编写一个测试类ProxyTest
package com.proxy.test2;
import java.lang.reflect.Proxy; public class ProxyTest { public static void main(String[] args) { //设置为true,会在工程根目录生成$Proxy0.class代理类(com.sun.proxy.$Proxy0.class) System.getProperties().put( "sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); String saveGeneratedFiles = System.getProperty("sun.misc.ProxyGenerator.saveGeneratedFiles"); System.out.println(saveGeneratedFiles); HelloTest helloWord = new HelloTestImpl(); CustomInvocationHandler customInvocationHandler = new CustomInvocationHandler( helloWord); //通过Proxy.newProxyInstance生成代理对象 HelloTest proxy = (HelloTest) Proxy.newProxyInstance( HelloTest.class.getClassLoader(), helloWord.getClass().getInterfaces(), customInvocationHandler); //调用say方法 proxy.say("test"); } }
5.运行测试类
true
Before invocation
Hello:test
After invocation
以上5步编写了一个JDK动态代理的例子,到底是如果代理的呢??
首先看ProxyTest 类中
HelloTest proxy = (HelloTest) Proxy.newProxyInstance(
HelloTest.class.getClassLoader(),
helloWord.getClass().getInterfaces(), customInvocationHandler);
查看Proxy.newProxyInstance源码:(JDK版本为jdk1.7.0_80)
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException { if (h == null) { throw new NullPointerException(); } 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. */ //获取代理类的实例 try { final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) { // create proxy instance with doPrivilege as the proxy class may // implement non-public interfaces that requires a special permission return AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { return newInstance(cons, ih); } }); } else { return newInstance(cons, ih); } } catch (NoSuchMethodException e) { throw new InternalError(e.toString()); } }
查看getProxyClass0方法
/**
* Generate a proxy class. Must call the checkProxyAccess method
* to perform permission checks before calling this.
*/
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
// JDK对代理进行了缓存,如果已经存在相应的代理类,则直接返回,否则才会通过ProxyClassFactory来创建代理
return proxyClassCache.get(loader, interfaces);
}
点击proxyClassCache
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
点击ProxyClassFactory
/**
* A factory function that generates, defines and returns the proxy class given
* the ClassLoader and array of interfaces.
*/
private static final class ProxyClassFactory implements BiFunction<ClassLoader, Class<?>[], Class<?>> // 所有代理类名字的前缀 private static final String proxyClassNamePrefix = "$Proxy"; ///用于生成唯一代理类名称的下一个数字 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 /* * 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)) { String name = intf.getName(); int n = name.lastIndexOf('.'); String pkg = ((n == -1) ? "" : name.substring