动态代理之Waiter案例

Waiter接口

package com.mango.demo2;

public interface Waiter {
	public void serve();
}

接口的实现类,ManWaiter

package com.mango.demo2;

public class ManWaiter implements Waiter {

	public void serve() {
		System.out.println("服务中...");
	}
}


Demo:


package com.mango.demo2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.junit.Test;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader;

public class Demo2 {
	@Test
	public void fun1(){
		
		ManWaiter manWaiter = new ManWaiter();
		
		ClassLoader loader = this.getClass().getClassLoader();
		Class[] interfaces = {Waiter.class};
		InvocationHandler h = new WaiterInvocationHandler(manWaiter);//参数manWaiter表示目标对象
		//得到代理对象,代理对象就是在目标对象的基础上进行了增强的对象
		Waiter waiterProxy = (Waiter) Proxy.newProxyInstance(loader, interfaces, h);
		waiterProxy.serve();
	}
}

class WaiterInvocationHandler implements InvocationHandler{
	
	private Waiter waiter;//目标对象
	
	public WaiterInvocationHandler(Waiter waiter){
		this.waiter = waiter;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		
		System.out.println("你好");//增强
		this.waiter.serve();
		System.out.println("再见");//增强
		
		return null;
	}
	
}


猜你喜欢

转载自blog.csdn.net/dear_mango/article/details/78305488