DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
JDK Dynamic Proxy
// First create the interface and its impl
// Then create the Proxy class implementing InvocationHandler interface
// create a Proxy using Proxy class static method createProxyInstance passing
// handles to classloader, interface and proxy impl.
package com.aop.one;
public interface Feather {
public void color(String s);
}
package com.aop.one;
public class BirdFeather implements Feather{
@Override
public void color(String s) {
System.out.println("The color of the feather is : " + s);
}
}
package com.aop.one;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyFeather implements InvocationHandler {
private Object target;
public ProxyFeather(Object t)
{
this.target = t;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("Before testing for the colors of the feathers");
method.invoke(target, args);
System.out.println("After testing for the colors of the feathers");
return null;
}
public static Object createProxy(Object t)
{
return Proxy.newProxyInstance(t.getClass().getClassLoader(),
t.getClass().getInterfaces(),
new ProxyFeather(t));
}
public void setTarget(Object target) {
this.target = target;
}
}
package com.aop.one;
public class Tester {
public static void main(String[] args) {
Feather f = new BirdFeather();
Feather myProxy = (Feather)ProxyFeather.createProxy(f);
myProxy.color("Violet");
}
}





