Skip to content

Instantly share code, notes, and snippets.

@karanmalhi
Created June 14, 2011 18:59
Show Gist options
  • Save karanmalhi/1025593 to your computer and use it in GitHub Desktop.
Save karanmalhi/1025593 to your computer and use it in GitHub Desktop.
The proxy creation mechanism
package learnquest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ProxyFactory {
public static void main(String[] args) throws Exception {
Reversable<String> reverser = create(StringReverser.class);
String result = reverser.reverse("MIT");
List list = (List) create(ArrayList.class);
list.add(0, "MIT");
list.add(1, "Cambridge");
list.get(1);
}
public static <S,T extends S> S create(Class<T> clazz) throws Exception {
T instance = clazz.newInstance();
Object newProxyInstance = Proxy.newProxyInstance(
clazz.getClassLoader(), clazz.getInterfaces(),
new LoggingAspect(instance));
return (S) newProxyInstance;
}
}
class LoggingAspect implements InvocationHandler {
private Object target;
public LoggingAspect(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("Method " + method.getName() + " invoked with args "
+ Arrays.asList(args));
Object result = method.invoke(target, args);
System.out.println("Result of invoking "+method.getName()+" is "+result);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment