Created
August 1, 2018 08:49
-
-
Save andhikayuana/acc66de606dd8f73e2cee5a1bf212408 to your computer and use it in GitHub Desktop.
Proxy Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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