Created
May 31, 2012 13:04
-
-
Save sanpingz/2843299 to your computer and use it in GitHub Desktop.
动态代理
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 static com.mceiba.util.Print.*; | |
| import java.lang.reflect.*; | |
| import java.lang.reflect.Proxy; | |
| interface Something{ | |
| void doSomething(); | |
| void somethingElse(String arg); | |
| } | |
| class RealObjects implements Something{ | |
| public void doSomething() { println("doSomething"); } | |
| public void somethingElse(String arg) { println("somethingElse "+arg); } | |
| } | |
| class DynamicProxyHandler implements InvocationHandler{ | |
| private Object proxied; | |
| public DynamicProxyHandler(Object proxied) { this.proxied = proxied; } | |
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{ | |
| println("**** proxy: "+proxy.getClass()+", method: "+method+", args: "+args); | |
| if(args != null) | |
| for(Object arg : args) println(" "+arg); | |
| return method.invoke(proxied, args); | |
| } | |
| } | |
| public class DynamicProxy{ | |
| public static void consumer(Something iface){ | |
| iface.doSomething(); | |
| iface.somethingElse("bonn"); | |
| } | |
| public static void main(String[] args){ | |
| RealObjects real = new RealObjects(); | |
| consumer(real); | |
| Something proxy = (Something)Proxy.newProxyInstance( | |
| Something.class.getClassLoader(), | |
| new Class[]{ Something.class }, | |
| new DynamicProxyHandler(real)); | |
| consumer(proxy); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment