public class HelloServiceProxyFactory { public static HelloService getHelloServiceProxy( final HelloService helloService) { InvocationHandler handler = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before calling " + method);// Add some pre operations Object result = method.invoke(helloService, args); System.out.println("after calling " + method);// Add some postpone operations return result; }
};
Class classType = HelloService.class; return (HelloService) Proxy.newProxyInstance( classType.getClassLoader(), new Class[] { classType }, handler); } }
package proxy.cxz.org;
public class Main { public static void main(String[] args) { HelloService helloService = new HelloServiceImpl(); HelloService helloServiceProxy = HelloServiceProxyFactory .getHelloServiceProxy(helloService); System.out.println("The name of the proxy class: " + helloServiceProxy.getClass().getName()); System.out.println(helloServiceProxy.echo("hello")); System.out.println(helloServiceProxy.getTime()); } }