动态代理的小例子

public class XfProxy implements InvocationHandler{
	//绑定过来一个对象进行解析
	private Object obj;
	Logger log=Logger.getLogger(XfProxy.class.getName());
	public Object bind(Object obj1){
		this.obj=obj1;
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),this);
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// TODO Auto-generated method stub
		System.out.println(proxy.getClass().getName());
		System.out.println(method.getName());
		System.out.println(args);
		log.log(Level.INFO,method.getName()+"之前.....");
		method.invoke(obj, args);
		log.log(Level.INFO,method.getName()+"之后...");
		
		return obj;
	}
	public static void main(String[] args) {
		//注意被代理的对象必须是接口
		WayTest wayTest=new WayTestImpl();
		XfProxy proxy=new XfProxy();
		wayTest=(WayTest)proxy.bind(wayTest);
		wayTest.tt("小李");
	}
	
}


public interface WayTest {
	public void tt(String name);
	
}

public class WayTestImpl implements WayTest{
	@Override
	public void tt(String name) {
		// TODO Auto-generated method stub
		System.out.println("hello"+name);
	}
}
//代理实际即真正在对象调用方法的前后,进行的一些切面的一些操作

猜你喜欢

转载自blog.csdn.net/bestxianfeng163/article/details/81160274