之前知道使用 JDK Proxy 和 Cglib 生成动态代理类。可是每次被问到,这二者的区别,性能比较等问题的时候,老是答不出来。其实仍是对这两个底层实现不够了解。html
先来讲一下 java 自带的 动态代理。JDK的代理咱们用到的就是两个类 Proxy 和 InvocationHandlerjava
public interface FooBarService { int getOrder(); }
public class FooBarServiceImpl implements FooBarService{ @Override public int getOrder() { System.out.println("真正的业务调用"); return 1; } }
package lujing.sample.core.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class FooBarServiceProxy implements InvocationHandler{ private FooBarService target = null; public FooBarServiceProxy(FooBarService fooBarService){ target = fooBarService; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("其实我是个代理"); return method.invoke(target, args); } public FooBarService getProxy(){ return (FooBarService)Proxy.newProxyInstance(FooBarServiceProxy.class.getClassLoader(), new Class[]{FooBarService.class}, this); } }
运行输出:apache
public class Launcher { public static void main(String[] args) { FooBarServiceProxy proxy = new FooBarServiceProxy(new FooBarServiceImpl()); FooBarService service = proxy.getProxy(); System.out.println(service.getClass().getName()); System.out.println(service.getOrder()); } }
com.sun.proxy.$Proxy0 其实我是个代理 真正的业务调用 1
@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); } /* * 生成代理类 */ Class<?> cl = getProxyClass0(loader, intfs); /* * Invoke its constructor with the designated invocation handler. */ try { // 获取构造方法 // private static final Class<?>[] constructorParams = // { InvocationHandler.class }; 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()); } }
从上面代码看出大概作了3步:缓存
1. 生成了一个新的代理 Class app
2. 获取代理类的构造函数。这个代理Class的构造函数,须要传一个 InvocationHandler,这个InvocationHandler就是咱们须要本身实现的接口。maven
3. 根据构造函数实例化一个代理类ide
这3步的核心就是生成代理类Class函数
/** * 生成代理Class */ private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) { if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); } // 若是须要的代理Class已经建立过,就直接使用缓存 // 不然 , 经过 ProxyClassFactory 建立代理类 return proxyClassCache.get(loader, interfaces); }
proxyClassCache.get 的处理正如上面说到的:源码分析
1. 若是须要的代理Class已经建立过,就直接使用缓存
2. 不然 , 经过 ProxyClassFactory 建立代理类性能
public V get(K key, P parameter) { Objects.requireNonNull(parameter); expungeStaleEntries(); // 只有被同一个 ClassLoader 加载的类,才算同一个类。因此这里Java Proxy 以 ClassLoader // 做为一个Key,分类去缓存 Object cacheKey = CacheKey.valueOf(key, refQueue); // ClassLoader 对应的 代理信息 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; } } // subKeyFactory.apply 正真的建立 代理 Class 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); } } } }
@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(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 + "."; } /* * 代理类名称如:com.sun.proxy.$Proxy0 */ long num = nextUniqueNumber.getAndIncrement(); String proxyName = proxyPkg + proxyClassNamePrefix + num; /* * 生成二进制字节码 */ byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces); try { // 二进制转Class,这里调的是 native 本地方法 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 生成字节码数据,ProxyGenerator 没有源代码,不过网上查一下仍是有源码的,这里参考的是 openJDK的源码:
public static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) { ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags); //真正生成字节码的方法 final byte[] classFile = gen.generateClassFile(); //若是saveGeneratedFiles为true 则生成字节码文件,因此在开始咱们要设置这个参数 //固然,也能够经过返回的bytes本身输出 if (saveGeneratedFiles) { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() { public Void run() { try { int i = name.lastIndexOf('.'); Path path; if (i > 0) { Path dir = Paths.get(name.substring(0, i).replace('.', File.separatorChar)); Files.createDirectories(dir); path = dir.resolve(name.substring(i+1, name.length()) + ".class"); } else { path = Paths.get(name + ".class"); } Files.write(path, classFile); return null; } catch (IOException e) { throw new InternalError( "I/O exception saving generated file: " + e); } } }); } return classFile; }
核心仍是在 generateClassFile()上
private byte[] generateClassFile() { /* ============================================================ * Step 1: Assemble ProxyMethod objects for all methods to generate proxy dispatching code for. * 步骤1:为全部方法生成代理调度代码,将代理方法对象集合起来。 */ //增长 hashcode、equals、toString方法 addProxyMethod(hashCodeMethod, Object.class); addProxyMethod(equalsMethod, Object.class); addProxyMethod(toStringMethod, Object.class); //增长接口方法 for (Class<?> intf : interfaces) { for (Method m : intf.getMethods()) { addProxyMethod(m, intf); } } /* * 验证方法签名相同的一组方法,返回值类型是否相同;意思就是重写方法要方法签名和返回值同样 */ for (List<ProxyMethod> sigmethods : proxyMethods.values()) { checkReturnTypes(sigmethods); } /* ============================================================ * Step 2: Assemble FieldInfo and MethodInfo structs for all of fields and methods in the class we are generating. * 为类中的方法生成字段信息和方法信息 */ try { //增长构造方法 methods.add(generateConstructor()); for (List<ProxyMethod> sigmethods : proxyMethods.values()) { for (ProxyMethod pm : sigmethods) { // add static field for method's Method object fields.add(new FieldInfo(pm.methodFieldName, "Ljava/lang/reflect/Method;", ACC_PRIVATE | ACC_STATIC)); // generate code for proxy method and add it methods.add(pm.generateMethod()); } } //增长静态初始化信息 methods.add(generateStaticInitializer()); } catch (IOException e) { throw new InternalError("unexpected I/O Exception", e); } if (methods.size() > 65535) { throw new IllegalArgumentException("method limit exceeded"); } if (fields.size() > 65535) { throw new IllegalArgumentException("field limit exceeded"); } /* ============================================================ * Step 3: Write the final class file. * 步骤3:编写最终类文件 */ /* * Make sure that constant pool indexes are reserved for the following items before starting to write the final class file. * 在开始编写最终类文件以前,确保为下面的项目保留常量池索引。 */ cp.getClass(dotToSlash(className)); cp.getClass(superclassName); for (Class<?> intf: interfaces) { cp.getClass(dotToSlash(intf.getName())); } /* * Disallow new constant pool additions beyond this point, since we are about to write the final constant pool table. * 设置只读,在这以前不容许在常量池中增长信息,由于要写常量池表 */ cp.setReadOnly(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); // 这里就是安装字节码规范写 二进制 数据了 try { // u4 magic; dout.writeInt(0xCAFEBABE); // u2 次要版本; dout.writeShort(CLASSFILE_MINOR_VERSION); // u2 主版本 dout.writeShort(CLASSFILE_MAJOR_VERSION); cp.write(dout); // (write constant pool) // u2 访问标识; dout.writeShort(accessFlags); // u2 本类名; dout.writeShort(cp.getClass(dotToSlash(className))); // u2 父类名; dout.writeShort(cp.getClass(superclassName)); // u2 接口; dout.writeShort(interfaces.length); // u2 interfaces[interfaces_count]; for (Class<?> intf : interfaces) { dout.writeShort(cp.getClass( dotToSlash(intf.getName()))); } // u2 字段; dout.writeShort(fields.size()); // field_info fields[fields_count]; for (FieldInfo f : fields) { f.write(dout); } // u2 方法; dout.writeShort(methods.size()); // method_info methods[methods_count]; for (MethodInfo m : methods) { m.write(dout); } // u2 类文件属性:对于代理类来讲没有类文件属性; dout.writeShort(0); // (no ClassFile attributes for proxy classes) } catch (IOException e) { throw new InternalError("unexpected I/O Exception", e); } return bout.toByteArray(); }
这里咱们很清楚的看到,在建立构造函数的时候,使用了 InvocationHandler 做为入参:
/** * Generate the constructor method for the proxy class. */ private MethodInfo generateConstructor() throws IOException { MethodInfo minfo = new MethodInfo( "<init>", "(Ljava/lang/reflect/InvocationHandler;)V", ACC_PUBLIC); DataOutputStream out = new DataOutputStream(minfo.code); code_aload(0, out); code_aload(1, out); out.writeByte(opc_invokespecial); out.writeShort(cp.getMethodRef( superclassName, "<init>", "(Ljava/lang/reflect/InvocationHandler;)V")); out.writeByte(opc_return); minfo.maxStack = 10; minfo.maxLocals = 2; minfo.declaredExceptions = new short[0]; return minfo; }
/** * Add another method to be proxied, either by creating a new * ProxyMethod object or augmenting an old one for a duplicate * method. * * "fromClass" indicates the proxy interface that the method was * found through, which may be different from (a subinterface of) * the method's "declaring class". Note that the first Method * object passed for a given name and descriptor identifies the * Method object (and thus the declaring class) that will be * passed to the invocation handler's "invoke" method for a given * set of duplicate methods. */ private void addProxyMethod(Method m, Class fromClass) { String name = m.getName(); Class[] parameterTypes = m.getParameterTypes(); Class returnType = m.getReturnType(); Class[] exceptionTypes = m.getExceptionTypes(); String sig = name + getParameterDescriptors(parameterTypes); List<ProxyMethod> sigmethods = proxyMethods.get(sig); if (sigmethods != null) { for (ProxyMethod pm : sigmethods) { if (returnType == pm.returnType) { /* * Found a match: reduce exception types to the * greatest set of exceptions that can thrown * compatibly with the throws clauses of both * overridden methods. */ List<Class> legalExceptions = new ArrayList<Class>(); collectCompatibleTypes( exceptionTypes, pm.exceptionTypes, legalExceptions); collectCompatibleTypes( pm.exceptionTypes, exceptionTypes, legalExceptions); pm.exceptionTypes = new Class[legalExceptions.size()]; pm.exceptionTypes = legalExceptions.toArray(pm.exceptionTypes); return; } } } else { sigmethods = new ArrayList<ProxyMethod>(3); proxyMethods.put(sig, sigmethods); } sigmethods.add(new ProxyMethod(name, parameterTypes, returnType, exceptionTypes, fromClass)); }
Java中生成的字节码是二进制数据,并且不像咱们以前能够直接拿到.class文件。那这个怎么导出呢?
这个时候,Java代理机制就起做用了。
2.1 定义代理入口
public class Launcher { /** * Java 代理入口 * @param agentArgs * @param inst */ public static void premain(String agentArgs, Instrumentation inst) { inst.addTransformer(new ClassTransformer()); } }
2.2 导出字节码处理
public class ClassTransformer implements ClassFileTransformer{ /** * JDK 生成的代理的命名: com.sun.proxy.$Proxy0 */ private static final String PROXY_PREFIX = "com/sun/proxy/$Proxy"; private String DEFAULT_FILE_PATH = "F://proxy.class"; private String filePath = DEFAULT_FILE_PATH; @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if(shouldExport(loader, className, classBeingRedefined)){ doExportClass(loader, className, classBeingRedefined, protectionDomain, classfileBuffer); } return classfileBuffer; } /** * 导出Class文件 * @param loader * @param className * @param classBeingRedefined * @param protectionDomain * @param classfileBuffer */ private void doExportClass(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { try { FileOutputStream fos; File file = new File(filePath); if(file.exists()){ file.createNewFile(); } fos = new FileOutputStream(file); fos.write(classfileBuffer); fos.close(); System.out.println("尝试将" + className + "写入到文件" + filePath + "成功"); } catch (Exception e) { System.out.println("尝试将" + className + "写入到文件" + filePath + "失败"); } } /** * 是否须要导出 * @param loader * @param className * @param classBeingRedefined * @return */ private boolean shouldExport(ClassLoader loader, String className, Class<?> classBeingRedefined) { return className.startsWith(PROXY_PREFIX); } }
2.3 maven打包参数,最主要是Premain-Class
<build> <finalName>agent</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifestEntries> <Premain-Class> me.kimi.instrument.Launcher </Premain-Class> </manifestEntries> </archive> </configuration> </plugin> </plugins> </build>
clean package 就导出一个 agent.jar啦
而后run configuration 加入代理jar:
运行一下代理类就导出到 proxy.class文件了。而后找一个反编译软件(个人是jad):
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) package com.sun.proxy; import java.lang.reflect.*; import lujing.sample.core.proxy.FooBarService; public final class $Proxy0 extends Proxy implements FooBarService { // 构造函数,接受 InvocationHandler 参数 public $Proxy0(InvocationHandler invocationhandler) { super(invocationhandler); } public final boolean equals(Object obj) { try { return ((Boolean)super.h.invoke(this, m1, new Object[] { obj })).booleanValue(); } catch(Error _ex) { } catch(Throwable throwable) { throw new UndeclaredThrowableException(throwable); } } public final int hashCode() { try { return ((Integer)super.h.invoke(this, m0, null)).intValue(); } catch(Error _ex) { } catch(Throwable throwable) { throw new UndeclaredThrowableException(throwable); } } public final int getOrder() { try { return ((Integer)super.h.invoke(this, m3, null)).intValue(); } catch(Error _ex) { } catch(Throwable throwable) { throw new UndeclaredThrowableException(throwable); } } public final String toString() { try { return (String)super.h.invoke(this, m2, null); } catch(Error _ex) { } catch(Throwable throwable) { throw new UndeclaredThrowableException(throwable); } } private static Method m1; private static Method m0; private static Method m3; private static Method m2; static { try { m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") }); m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]); m3 = Class.forName("lujing.sample.core.proxy.FooBarService").getMethod("getOrder", new Class[0]); m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]); } catch(NoSuchMethodException nosuchmethodexception) { throw new NoSuchMethodError(nosuchmethodexception.getMessage()); } catch(ClassNotFoundException classnotfoundexception) { throw new NoClassDefFoundError(classnotfoundexception.getMessage()); } } }
从上面的代码能够看到,代理类实现了须要代理的接口,同时每一个方法都是委托给 InvocationHandler 的 invoke 方法。在生成代理发方法的时候,就知道 代理接口的方法是哪个。