java 1.8動的な代理ソースの深さ分析


JDK 8の動的な代理ソース分析
ダイナミックエージェントの基本使用は詳しく紹介しません。
例:

class proxyed implements pro{
 @Override
 public void text() {
  System.err.println("   ");
 }
}

interface pro {
 void text();
}

public class JavaProxy implements InvocationHandler {
  private Object source;
  public JavaProxy(Object source) {
   super();
   this.source = source;
  }
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   System.out.println("before");
   Object invoke = method.invoke(source, args);
   System.out.println("after");
   return invoke;
  }
  public Object getProxy(){
   return Proxy.newProxyInstance(getClass().getClassLoader(), source.getClass().getInterfaces(), this);
  }
  public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
   //   ,   
   //1.  saveGeneratedFiles  true    class         
   System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
   //2.       
   Class proxyClazz = Proxy.getProxyClass(pro.class.getClassLoader(),pro.class);
   //3.          ,       InvocationHandler.class
   Constructor constructor = proxyClazz.getConstructor(InvocationHandler.class);
   //4.               ,     InvocationHandler    
   pro iHello = (pro) constructor.newInstance(new JavaProxy(new proxyed()));
   //5.            
   iHello.text();
   //   ,  JDK     ,   2~4 
   Proxy.newProxyInstance(JavaProxy.class.getClassLoader(),proxyed.class.getInterfaces(),new JavaProxy(new proxyed()));
  }
}
入り口:newProxyInstance

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException {
  //Objects.requireNonNull     ,          null    ,     
  Objects.requireNonNull(h);
  //clone         
  final Class<?>[] intfs = interfaces.clone();
  //          
  final SecurityManager sm = System.getSecurityManager();
  if (sm != null) {
   //Reflection.getCallerClass              ;loader:       
   //       、         
   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);
   }
   //    
   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);
  }
 }
上の分析から、newProxyInstanceは私達にプロキシ類を生成するように手伝いました。
私達は重点的に分析して代理種類を生成します。
get ProxyClass 0

/**
  * a cache of proxy classes:           
  * KeyFactory:       ,       key    ,              ;   key         WeakReference(key0、key1、key2、keyX),      (hash )
  * ProxyClassFactory:        
  *   ,      BiFunction<ClassLoader, Class<?>[], Object>  
  */
 private static final WeakCache<ClassLoader, Class<?>[], Class<?>> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

 /**
  * Generate a proxy class. Must call the checkProxyAccess method
  * to perform permission checks before calling this.
  *      ,        checkProxyAccess    ,  newProxyInstance       
  */
 private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) {
  //         <65535;            
  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
  //       ,     ,     
  return proxyClassCache.get(loader, interfaces);
 }
proxyClass Cache.get

public V get(K key, P parameter) {
  //key:    ;parameter:    
  Objects.requireNonNull(parameter);
  //     GC      
  expungeStaleEntries();

  //CacheKey    ,refQueue           ;    CacheKey
  Object cacheKey = CacheKey.valueOf(key, refQueue);
  
  //map    ,  valuesMap    
  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   KeyFactory,apply       key
  Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
  //Factory    supplier,           Factory,   get  
  Supplier<V> supplier = valuesMap.get(subKey);
  Factory factory = null;
  
  //      CAS+                  
  while (true) {
   if (supplier != null) {
    //      ,     get  , supplier          ,    Factory new   
    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);
    }
   }
  }
 }
supplier.get
この方法はProxyClass Factoryのアプリを呼び出すことができます。
ProxyClass Factory.apply

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
  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.
    * proxyClassNamePrefix = $Proxy
    * nextUniqueNumber       ,       ,      ,   :$Proxy0,$Proxy1......
    */
  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());
  }
 }
ProxyGenerator.generate ProxyClass

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;
 }
最終的な方法

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();
 }
生成されたバイトコードの逆コンパイル

final class $Proxy0 extends Proxy implements pro {
  //fields 
  private static Method m1;
  private static Method m2;
  private static Method m3;
  private static Method m0;

  public $Proxy0(InvocationHandler var1) throws {
   super(var1);
  }

  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);
   }
  }

  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);
   }
  }

  public final void text() throws {
   try {
    //          invoke   
    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);
   }
  }

  static {
   try {
    //                  
    m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[]{Class.forName("java.lang.Object")});
    m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
    m3 = Class.forName("spring.commons.api.study.CreateModel.pro").getMethod("text", new Class[0]);
    m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
   } catch (NoSuchMethodException var2) {
    throw new NoSuchMethodError(var2.getMessage());
   } catch (ClassNotFoundException var3) {
    throw new NoClassDefFoundError(var3.getMessage());
   }
  }
 }
以上のjava 1.8の動的な代理ソースの深さ分析は、小編集のすべてのコンテンツを共有することです。皆様に参考にしていただければと思います。どうぞよろしくお願いします。