您的位置:首页 > 编程语言 > Java开发

JDK动态代理实例

2010-12-03 00:07 387 查看
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.Hello;

public class SayHello implements Hello{

	@Override
	public void hello() {
		// TODO Auto-generated method stub
		System.out.println("hello");
	}
	
	static class MyInvocationHandler implements InvocationHandler{
		private Object target;
		public MyInvocationHandler(Object target){
			this.target=target;
		}
		
		@Override
		public Object invoke(Object proxy, Method method, Object[] args)
				throws Throwable {
			// TODO Auto-generated method stub
			System.out.println(method.getName()+"-------start");
			Object result=method.invoke(target, args);
			System.out.println(method.getName()+"--------end");
			return result;
		}
	}
	
	static class ProxyFactory{
		InvocationHandler h;
		Class cls;
		public ProxyFactory(String className,InvocationHandler h) throws ClassNotFoundException{
			cls=Class.forName(className);
			this.h=h;
		}
		
		public Object create(){
			return Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), h);
		}
	}
	
	public static void main(String[] args) throws ClassNotFoundException {
		Hello s=new SayHello();
		InvocationHandler h=new MyInvocationHandler(s);
		ProxyFactory proxyFactory=new ProxyFactory(SayHello.class.getName(), h);
		Hello sf=(Hello) proxyFactory.create();
		sf.hello();
	}

}

-----------------会输出
hello-------start
hello--------end




大家可以debug,看看代码怎么走的。

下次研究过后会给出更详细的说明,^_^ 要睡觉了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: