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

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"); } } }

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