18.5.1使用Proxy和InvocationHandler创建动态代理

package d18_5_1;

public interface Person {

	void walk();

	void sayHello(String name);
}

  

package d18_5_1;
/**
 * proxy提供了两个方法来创建动态代理类和动态代理实例
 * static Class<?> getProxyClass(ClassLoader loader,Class<?>... interface)
 * static Object newProxyInstance(ClassLoader loader,Class<?>[] interface,InvocationHandler handler)
 */
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

class MyInvocationHandler implements InvocationHandler {
	/**
	 * 执行动态代理对象的所有方法时,都会被替换成执行如下的invoke的方法
	 * 其中:
	 *    proxy代表动态代理对象
	 *    method代表正在执行的方法
	 *    args代表执行代理对象方法时传入的实参
	 */
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("正在执行的方法:" + method);
		if (args != null) {
			System.out.println("下面是执行该方法时传入的实参");
			for (Object val : args) {
				System.out.println(val);
			}
		} else {
			System.out.println("调用该方法无须实参!");
		}
		return null;
	}
}

public class ProxyTest {
	public static void main(String[] args) {
		//创建以恶搞InvocationHandler对象
		//InvocationHandler handler=new MyInvocationHandler();
		InvocationHandler handler=new MyInvocationHandler();
		//使用指定的InvocationHandler来生成一个动态代理对象
		Person p=(Person)Proxy.newProxyInstance(Person.class.getClassLoader(),
				new Class[]{Person.class}, handler);
		//调用动态代理对象的walk()和sayHello()方法
		p.walk();
		p.sayHello("齐天大圣");
		
		
	}
}

  

原文地址:https://www.cnblogs.com/1020182600HENG/p/7360817.html