`
leeo1124
  • 浏览: 23796 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JDK动态代理

    博客分类:
  • java
阅读更多
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();
	}
}
1
0
分享到:
评论
2 楼 leeo1124 2012-06-28  
w156445045 写道
动态代理是干嘛的~

这个嘛,你还是google 或者 百度一下吧 三言两语也说不清
1 楼 w156445045 2012-06-27  
动态代理是干嘛的~

相关推荐

Global site tag (gtag.js) - Google Analytics