JDK动态代理

1、代理接口
/**
 * 代理接口
 * 
 * @author Leeo
 * 
 */
interface Work {

	void task();

}


2、代理接口实现类
/**
 * 代理接口实现类
 * 
 * @author Leeo
 * 
 */
class WorkImpl implements Work {

	public WorkImpl() {

	}

	public void task() {
		System.out.println("上班了...");
	}

}


3、自定义一个代理器,实现InvocationHandler接口
/**
 * 自定义代理器
 * 
 * @author Leeo
 * 
 */
class MyInvocationHandler implements InvocationHandler {

	private Object taget;

	public MyInvocationHandler() {

	}

	public MyInvocationHandler(Object obj) {
		taget = obj;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {

		System.out.println("befor...");
		Object obj = method.invoke(taget, args);
		System.out.println("after...");

		return obj;
	}

}


4、代理测试
/**
 * 动态代理测试
 * @author Leeo
 *
 */
public class ProxyTest {

	public static void main(String[] args) {

		Work target= new WorkImpl();
		InvocationHandler handler = new MyInvocationHandler(target);

		Work work = (Work) Proxy.newProxyInstance(
				target.getClass().getClassLoader(), 
				target.getClass().getInterfaces(), handler);
		work.task();
	}
}

你可能感兴趣的:(java,proxy,JDK动态代理,leeo)