Creating a Proxy Object - Java Reflection

Java examples for Reflection:Proxy

Description

Creating a Proxy Object

Demo Code


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

public class Main {
  public static void main(String[] args) throws Exception {
    MyInterface myintf = (MyInterface) Proxy.newProxyInstance(
        MyInterface.class.getClassLoader(), new Class[] { MyInterface.class },
        new ProxyClass(new MyInterfaceImpl()));
    myintf.method();/*from  w ww .  j  a  va  2s .c o  m*/
  }
}

interface MyInterface {
  void method();
}

class MyInterfaceImpl implements MyInterface {
  public void method() {
  }
}

class ProxyClass implements InvocationHandler {
  Object obj;

  public ProxyClass(Object o) {
    obj = o;
  }

  public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
    Object result = null;
    try {
      result = m.invoke(obj, args);
    } catch (InvocationTargetException e) {
    } catch (Exception eBj) {
    } finally {
      // Do something after the method is called ...
    }
    return result;
  }
}

Related Tutorials