动态代理

应用 事物 日志 权限 等。。。

 

http://langyu.iteye.com/blog/410071

 proxy源码 O(∩_∩)O

http://hi.baidu.com/malecu/item/9e0edc115cb597a1feded5a0

 

public class LogInterceptor implements InvocationHandler {

	private Object target;
	
	public void beforeMethod(){
		System.out.println("start now...");
	}
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		this.beforeMethod();
		method.invoke(target,args);
		return null;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

	public Object getTarget() {
		return target;
	}

}

 

@Test
	public void testProxy() throws Exception{
		UserDao userDao = new UserDaoImpl();
		LogInterceptor li = new LogInterceptor();
		li.setTarget(userDao);
		UserDao userDaoProxy = (UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(), userDao.getClass().getInterfaces(),li);
		System.out.println(userDaoProxy.getClass());//class $proxy4

		userDaoProxy.save(new User());
	}

 

//大概模拟 $proxy4
//本例中
public class $proxy4 implements UserDao{
	save(User u){
		Method m= UserDao.getClass.getMethod();
		li.invoke(this,m.u);//代理对象,方法,参数
	}
}

 

 

你可能感兴趣的:(动态代理)