package org.web.proxy; import java.lang.reflect.Method; public class Context implements MethodProxy { public String method = null; public String service = null; public String methodStatus = null; public String setMethod(String method) { if(method == null) { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } this.method = method; return "ok"; } public String setService(String service) { if(service == null) { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } this.service = service; return "ok"; } public String invokeMethod() { if(this.service == null || this.method == null) { System.out.println("No Service || No Method"); System.exit(-1); } else { try { Class<?> cla = Class.forName("org.web.service.HelloService"); Method[] methods = cla.getMethods(); Method m = cla.getMethod(this.method, String.class); this.methodStatus = String.valueOf(m.invoke(cla.newInstance(), "fuckyou")); } catch (Exception e) { e.printStackTrace(); } } return this.methodStatus; } }
这是最重要的一个类。。。里面用到了反射。。
package org.web.proxy; //定义的一些接口方法。。 public interface MethodProxy { //setMethod public String setMethod(String method); //setService public String setService(String service); //invoke method public String invokeMethod(); }
package org.web; import org.web.proxy.Context; public class ProxyPattern { public static void main(String[] args) { Context context = new Context(); context.setService("org.web.service.HelloService"); context.setMethod("helloWorld"); System.out.println("Main Method :" + context.invokeMethod()); } }
Main方法。其实就是起一个调用的过程。。。。
package org.web.service; public class HelloService { public String helloWorld(String name) { System.out.println("HelloService: " + name); return name; } }
service 类。
总结。。。感觉还是封装。。。。。。其它,没了。。。