Java dynamic proxy details and examples

  • 2020-05-30 20:05:53
  • OfStack

Java dynamic proxy

Agent design pattern

Definition: provide a proxy for other objects to control access to this object.

Dynamic proxy usage

The java dynamic proxy mechanism implements the design concept of the proxy pattern in a clever way.

Proxy pattern sample code


public interface Subject  
{  
 public void doSomething();  
}  
public class RealSubject implements Subject  
{  
 public void doSomething()  
 {  
  System.out.println( "call doSomething()" );  
 }  
}  
public class ProxyHandler implements InvocationHandler  
{  
 private Object proxied;  
   
 public ProxyHandler( Object proxied )  
 {  
  this.proxied = proxied;  
 }  
   
 public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable  
 {  
  // This can be done before the specific target object is transferred 1 Some functional processing 

  // The method of transferring specific target objects 
  return method.invoke( proxied, args); 
  
  // After the specific target object is transferred, it can be executed 1 Some functional processing 
 }  
} 


import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Method;  
import java.lang.reflect.Proxy;  
import sun.misc.ProxyGenerator;  
import java.io.*;  
public class DynamicProxy  
{  
 public static void main( String args[] )  
 {  
  RealSubject real = new RealSubject();  
  Subject proxySubject = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(), 
   new Class[]{Subject.class}, 
   new ProxyHandler(real));
     
  proxySubject.doSomething();
  
  //write proxySubject class binary data to file  
  createProxyClassFile();  
 }  
   
 public static void createProxyClassFile()  
 {  
  String name = "ProxySubject";  
  byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { Subject.class } );  
  try 
  {  
   FileOutputStream out = new FileOutputStream( name + ".class" );  
   out.write( data );  
   out.close();  
  }  
  catch( Exception e )  
  {  
   e.printStackTrace();  
  }  
 }  
} 

Dynamic proxy internal implementation

First, let's look at the code for class Proxy that implements the main static variables of Proxy


//  Mapping table: used to maintain the class loader object to its corresponding proxy class cache 
private static Map loaderToCache = new WeakHashMap(); 

//  Tag: used for tagging 1 Four dynamic proxy classes are being created 
private static Object pendingGenerationMarker = new Object(); 

//  Synchronization table: records the dynamic proxy class types that have been created, mainly by methods  isProxyClass  Make relevant judgments 
private static Map proxyClasses = Collections.synchronizedMap(new WeakHashMap()); 

//  The associated call handler reference 
protected InvocationHandler h;

The construction method of Proxy


//  Due to the  Proxy  Internal never calls the constructor directly, so  private  Type means that any call is forbidden 
private Proxy() {} 

//  Due to the  Proxy  Internal never calls the constructor directly, so  protected  That means only subclasses can call it 
protected Proxy(InvocationHandler h) {this.h = h;} 

Proxy static method newProxyInstance


public static Object newProxyInstance(ClassLoader loader, Class<?>[]interfaces,InvocationHandler h) throws IllegalArgumentException { 
  //  check  h  Not empty, otherwise throw exception 
  if (h == null) { 
    throw new NullPointerException(); 
  } 

  //  Gets with the specified class loader and 1 Group interface-related proxy class type object 
  Class cl = getProxyClass(loader, interfaces); 

  //  Gets the constructor object through reflection and generates a proxy class instance 
  try { 
    Constructor cons = cl.getConstructor(constructorParams); 
    return (Object) cons.newInstance(new Object[] { h }); 
  } catch (NoSuchMethodException e) { throw new InternalError(e.toString()); 
  } catch (IllegalAccessException e) { throw new InternalError(e.toString()); 
  } catch (InstantiationException e) { throw new InternalError(e.toString()); 
  } catch (InvocationTargetException e) { throw new InternalError(e.toString()); 
  } 
}


The getProxyClass method of class Proxy calls the generateProxyClass method of class ProxyGenerator to produce ProxySubject.class's base 2 data:


public static byte[] generateProxyClass(final String name, Class[] interfaces)

We can import sun.misc.ProxyGenerator, call the generateProxyClass method to produce binary data, write to the file, and then look at the internal implementation through the decompile tool. Decompiled ProxySubject.java Proxy static method newProxyInstance


import java.lang.reflect.*;  
public final class ProxySubject extends Proxy  
  implements Subject  
{  
  private static Method m1;  
  private static Method m0;  
  private static Method m3;  
  private static Method m2;  
  public ProxySubject(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 void doSomething()  
  {  
    try 
    {  
      super.h.invoke(this, m3, null);  
      return;  
    }  
    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);  
    }  
  }  
  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("Subject").getMethod("doSomething", 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());  
    }  
  }  
} 

How ProxyGenerator generates class2 data internally can be referred to in the source code.


private byte[] generateClassFile() {  
 /* 
  * Record that proxy methods are needed for the hashCode, equals, 
  * and toString methods of java.lang.Object. This is done before 
  * the methods from the proxy interfaces so that the methods from 
  * java.lang.Object take precedence over duplicate methods in the 
  * proxy interfaces. 
  */ 
 addProxyMethod(hashCodeMethod, Object.class);  
 addProxyMethod(equalsMethod, Object.class);  
 addProxyMethod(toStringMethod, Object.class);  
 /* 
  * Now record all of the methods from the proxy interfaces, giving 
  * earlier interfaces precedence over later ones with duplicate 
  * methods. 
  */ 
 for (int i = 0; i < interfaces.length; i++) {  
   Method[] methods = interfaces[i].getMethods();  
   for (int j = 0; j < methods.length; j++) {  
  addProxyMethod(methods[j], interfaces[i]);  
   }  
 }  
 /* 
  * For each set of proxy methods with the same signature, 
  * verify that the methods' return types are compatible. 
  */ 
 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");  
 }  
 /* ============================================================ 
  * Step 3: Write the final class file. 
  */ 
 /* 
  * 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 (int i = 0; i < interfaces.length; i++) {  
   cp.getClass(dotToSlash(interfaces[i].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 {  
   /* 
    * Write all the items of the "ClassFile" structure. 
    * See JVMS section 4.1. 
    */ 
     // u4 magic;  
   dout.writeInt(0xCAFEBABE);  
     // u2 minor_version;  
   dout.writeShort(CLASSFILE_MINOR_VERSION);  
     // u2 major_version;  
   dout.writeShort(CLASSFILE_MAJOR_VERSION);  
   cp.write(dout);  // (write constant pool)  
     // u2 access_flags;  
   dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);  
     // u2 this_class;  
   dout.writeShort(cp.getClass(dotToSlash(className)));  
     // u2 super_class;  
   dout.writeShort(cp.getClass(superclassName));  
     // u2 interfaces_count;  
   dout.writeShort(interfaces.length);  
     // u2 interfaces[interfaces_count];  
   for (int i = 0; i < interfaces.length; i++) {  
  dout.writeShort(cp.getClass(  
    dotToSlash(interfaces[i].getName())));  
   }  
     // u2 fields_count;  
   dout.writeShort(fields.size());  
     // field_info fields[fields_count];  
   for (FieldInfo f : fields) {  
  f.write(dout);  
   }  
     // u2 methods_count;  
   dout.writeShort(methods.size());  
     // method_info methods[methods_count];  
   for (MethodInfo m : methods) {  
  m.write(dout);  
   }  
       // u2 attributes_count;  
   dout.writeShort(0); // (no ClassFile attributes for proxy classes)  
 } catch (IOException e) {  
   throw new InternalError("unexpected I/O Exception");  
 }  
 return bout.toByteArray(); 

conclusion

A typical dynamic proxy object creation process can be divided into the following four steps:

1. Create your own calling handler IvocationHandler handler = new InvocationHandlerImpl(...) by implementing the InvocationHandler interface ;

2. Create a dynamic proxy class by specifying ClassLoader objects and 1 group of interface for the Proxy class


Class clazz = Proxy.getProxyClass(classLoader,new Class[]{...});


3. Get the constructor of the dynamic proxy class through reflection mechanism, whose parameter type is the interface type of the calling processor


Constructor constructor = clazz.getConstructor(new Class[]{InvocationHandler.class});

4. Create a proxy class instance through the constructor, at which point the calling handler object is passed in as a parameter


import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Method;  
import java.lang.reflect.Proxy;  
import sun.misc.ProxyGenerator;  
import java.io.*;  
public class DynamicProxy  
{  
 public static void main( String args[] )  
 {  
  RealSubject real = new RealSubject();  
  Subject proxySubject = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(), 
   new Class[]{Subject.class}, 
   new ProxyHandler(real));
     
  proxySubject.doSomething();
  
  //write proxySubject class binary data to file  
  createProxyClassFile();  
 }  
   
 public static void createProxyClassFile()  
 {  
  String name = "ProxySubject";  
  byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { Subject.class } );  
  try 
  {  
   FileOutputStream out = new FileOutputStream( name + ".class" );  
   out.write( data );  
   out.close();  
  }  
  catch( Exception e )  
  {  
   e.printStackTrace();  
  }  
 }  
} 
0

To simplify object creation, the newInstance methods in the Proxy class encapsulate 2 to 4 steps to create the proxy object.

The generated ProxySubject inherits Proxy class to implement Subject interface, and the implemented Subject method actually calls the processor's invoke method, while the invoke method calls the method of the proxied object using reflection (Object result= method.invoke (proxied,args)).

a fly in the ointment

Sure, Proxy has been beautifully designed, but there is a small regret that it has never been able to get rid of the shackle of supporting only the interface agent, because it was designed to do so. Recall from 1 that the inheritance diagrams of dynamically generated proxy classes are destined to have a common parent class called Proxy. The inheritance mechanism of Java makes it impossible for these dynamic proxy classes to implement dynamic proxies to class, because multiple inheritance is inherently unfeasible in Java. There are many reasons to deny the need for class agents, but there are also some reasons to believe that it is better to support class dynamic agents. The separation of interfaces and classes, which was never obvious, only became so detailed in Java. If you consider only the declaration of a method and whether it is defined, there is a mixture of the two, and its name is abstract class. There is also inherent value in implementing dynamic proxies for abstract classes. In addition, there are a number of legacy classes that will never be dynamically brokering because they do not implement any interfaces. Such a variety, have to say a small regret. However, imperfection is not equal to not great, great is a kind of essence, Java dynamic agent is the zuo case.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: