Dynamic Proxies : Proxy Pattern « Design Pattern « Java Tutorial






import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface MyClass {

  void methodA(String s);

  void methodB(int i);

  String methodC(int i, String s);

}

public class DynamicProxyDemo {

  public static void main(String[] clargs) {
    MyClass prox = (MyClass) Proxy.newProxyInstance(MyClass.class.getClassLoader(), new Class[] { MyClass.class },
        new InvocationHandler() {
          public Object invoke(Object proxy, Method method, Object[] args) {
            System.out.println("Method = " + method);
            if (args != null) {
              System.out.println("args = ");
              for (int i = 0; i < args.length; i++)
                System.out.println("\t" + args[i]);
            }
            return null;
          }
        });
    System.out.println("about to call methodA");
    prox.methodA("hello");
    System.out.println("finish calling methodA");
    prox.methodB(47);
    prox.methodC(47, "hello");
  }
}








34.16.Proxy Pattern
34.16.1.Proxy: fronting for another object
34.16.2.The PoolManager using Proxy
34.16.3.Dynamic Proxies