Dynamic Proxy
发布日期:2021-09-30 23:31:50 浏览次数:27 分类:技术文章

本文共 2272 字,大约阅读时间需要 7 分钟。

package proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DProxy { public interface Subject { void request(String param); void response(String param); } public static class RealSubject implements Subject { public void request(String param) { System.out.println("This message is from RealSubject."); } public void response(String param) { System.out.println("This message is response from RealSubject."); } } public static class RealSubject2 implements Subject { public void request(String param) { System.out.println("This message is from RealSubject2:"+param); } public void response(String param) { System.out.println("This message is response from RealSubject2."); } } public static class AnotherSubject { public void request(String param) { System.out.println("This message is from AnotherSubject:"+param); } public void response(String param) { System.out.println("This message is response from AnotherSubject."+param); } } public static class DynamicSubject implements InvocationHandler { private Object object; public DynamicSubject(Object o) { this.object=o; } public Object invoke(Object proxy,Method method,Object[] args) throws Throwable { System.out.println("Dynamic Proxy's Method:"+method.getName()+" "+method.getDeclaringClass()); //System.out.println("Args:"+(String)args[0]); System.out.println(proxy.getClass().getName()); method.invoke(object, args); return null; } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Object real = new RealSubject(); //System.out.println(real); InvocationHandler handler=new DynamicSubject(real); Object proxyed = Proxy.newProxyInstance(real.getClass().getClassLoader(), real.getClass().getInterfaces(), handler); //System.out.println(proxyed); if(proxyed instanceof Subject) { Subject subProxy = (Subject)proxyed; subProxy.request(null); subProxy.response("response1"); } Object real2 = new RealSubject2(); handler=new DynamicSubject(real2); proxyed = Proxy.newProxyInstance(real2.getClass().getClassLoader(), real2.getClass().getInterfaces(), handler); if(proxyed instanceof Subject) { Subject subProxy = (Subject)proxyed; subProxy.request("Prameter2"); subProxy.response("response2"); } } }

转载地址:https://blog.csdn.net/iteye_14736/article/details/82033375 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:ubuntu MySQL访问时出现ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using
下一篇:Observer Pattern(观察者模式)

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月12日 00时05分50秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章