java dynamic proxy

package proxy.cxz.org;

import java.util.Date;

public interface HelloService {
	public String echo(String msg);
	public Date getTime();
}

package proxy.cxz.org;

import java.util.Date;

public class HelloServiceImpl implements HelloService {

	public String echo(String msg) {
		return "echo: " + msg;
	}

	public Date getTime() {
		return new Date();
	}

}

package proxy.cxz.org;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

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

你可能感兴趣的:(java)