http://toptech.geekaddict.net/
How to create a Proxy in Java
A proxy is an object that can wrap another object and expose the same interface. This proxy can be used the same way as the original object, but can contain extra functionality. It can be an important tool for Aspect-oriented programming. The following example shows how to make a proxy that logs the method calls of an object.
We define a logger proxy that wraps an object and log all method invocations on it.
class LoggerProxy implements InvocationHandler {
private Object proxiedObj;
private LoggerProxy(Object proxiedObj) {
this.proxiedObj = proxiedObj;
}
public Object invoke(Object proxy, Method method, Object[] args) {
try {
Object returnValue = method.invoke(proxiedObj, args);
String log = "LoggerProxy - method: " + method.getName() + " called on object: " + proxiedObj;
System.out.println(log);
return returnValue;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object wrapObject(Object proxiedObj) {
return Proxy.newProxyInstance(
proxiedObj.getClass().getClassLoader(),
proxiedObj.getClass().getInterfaces(),
new LoggerProxy(proxiedObj));
}
}
In this test application we define an interface for testing the proxy (Foo), and an implementing class (FooImpl). We create an instance of FooImpl, then wrap that object in a Logger proxy, then call some methods through the proxy.
interface Foo {
public void fooTest();
}
class FooImpl implements Foo {
public void fooTest() {
System.out.println("Foo: fooTest() called");
}
}
public class Test {
public static void main(String[] args) {
// create an instance of Foo
Foo f = new FooImpl();
// wrap the object f in a logger proxy. The type of the proxied object remains Foo.
Foo proxiedObject = (Foo) LoggerProxy.wrapObject(f);
// call a method through the proxy
proxiedObject.fooTest();
}
}