Simple facts about Java dynamic proxy 

Joined:
03/07/2011
Posts:
57

June 02, 2011 15:49:26    Last update: June 02, 2011 15:51:08
Facts:
  1. Dynamic proxy classes are generated by the Java runtime, from a list of interfaces given by the user.
  2. The generated proxy class implements all interfaces given by the user.
  3. The dynamic proxy class is not synthetic.
  4. The dynamic proxy class is useless without a user supplied InvocationHandler class, since there's only one constructor for the proxy class and it takes a InvocationHandler as parameter.


Example code:
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.io.FileFilter;
import java.io.Flushable;

public class ProxyTest {
    public static void main(String[] args) throws Exception {
	Class c = Proxy.getProxyClass(
	    ProxyTest.class.getClassLoader(),
	    FileFilter.class,
	    Flushable.class
	);

	// what's the class name
	System.out.println("Class: " + c.getName());

	// dynamic proxy is NOT synthetic
	System.out.println("isSynthetic: " + c.isSynthetic());

	// There's only one constructor, which takes InvocationHandler
	// as parameter.
	Constructor[] cons = c.getConstructors();
	for (int i = 0; i < cons.length; i++) {
	    Constructor con = cons[i];
	    Class[] paramTypes = con.getParameterTypes();
	    System.out.println("Constructor " + (i + 1) + " parameters:"); 

	    if (paramTypes.length == 0) {
		System.out.println("\tnone");
	    }

	    for (int j = 0; j < paramTypes.length; j++) {
		System.out.println("\t" + paramTypes[j].getName());
	    }
	    System.out.println();
	}

	// supports all methods in the listed interfaces
	// as well as those defined in Proxy and Object
	Method[] methods = c.getMethods();
	for (int i = 0; i < methods.length; i++) {
	    System.out.println("Method: " + methods[i].getName());
	}
    }
}

Output:
Class: $Proxy0
isSynthetic: false
Constructor 1 parameters:
        java.lang.reflect.InvocationHandler

Method: equals
Method: toString
Method: hashCode
Method: flush
Method: accept
Method: isProxyClass
Method: getProxyClass
Method: getInvocationHandler
Method: newProxyInstance
Method: wait
Method: wait
Method: wait
Method: getClass
Method: notify
Method: notifyAll

Share |
| Comment  | Tags