Skip to content

Instantly share code, notes, and snippets.

@andhikayuana
Created August 1, 2018 08:49
Show Gist options
  • Select an option

  • Save andhikayuana/acc66de606dd8f73e2cee5a1bf212408 to your computer and use it in GitHub Desktop.

Select an option

Save andhikayuana/acc66de606dd8f73e2cee5a1bf212408 to your computer and use it in GitHub Desktop.
Proxy Pattern
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) {
Original original = new Original();
Handler handler = new Handler(original);
If f = (If) Proxy.newProxyInstance(If.class.getClassLoader(),
new Class[] { If.class },
handler);
f.oriMethod("Hallo");
}
interface If {
void oriMethod(String s);
}
static class Original implements If {
public void oriMethod(String s) {
System.out.println(s);
}
}
static class Handler implements InvocationHandler {
private final If ori;
public Handler(If ori) {
this.ori = ori;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
System.out.println("BEFORE");
method.invoke(ori, args);
System.out.println("AFTER");
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment