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

java 动态代理实现

2015-09-09 18:15 567 查看
先附上项目结构:



步骤:

1.创建IFly接口:

package glut.proxy;
public interface IFly {
	void fly();
}


2.创建Bird类,并让它实现IFly:

package glut.proxy;
public class Bird implements IFly {
	public void fly() {
		System.out.println("A bird is flying");
	}
}


3.创建MyProxy类,并让它实现InvocationHandler

package glut.proxy;

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

public class MyProxy implements InvocationHandler {
	// 目标实例
	private Object targetInstance;

	// 不允许无参构造函数
	private MyProxy() {
		// TODO Auto-generated constructor stub
	}

	public MyProxy(Object targetInstance) {
		this.targetInstance = targetInstance;
	}

	/**
	 * Processes a method invocation on a proxy instance and returns the result.
	 * This method will be invoked on an invocation handler when a method is
	 * invoked on a proxy instance that it is associated with.
	 * 每次调用目标实例的方法时,会回调invoke方法
	 * @param 代理对象实例
	 * 
	 * @param 目标实例被调用的方法名
	 * 
	 * @param 目标实例被调用的方法的参数
	 * 
	 * @return 目标实例调用的方法的返回值
	 * 
	 * 
	 * @throws Throwable
	 *             the exception to throw from the method invocation on the
	 *             proxy instance. The exception's type must be assignable
	 *             either to any of the exception types declared in the
	 *             {@code throws} clause of the interface method or to the
	 *             unchecked exception types {@code java.lang.RuntimeException}
	 *             or {@code java.lang.Error}. If a checked exception is thrown
	 *             by this method that is not assignable to any of the exception
	 *             types declared in the {@code throws} clause of the interface
	 *             method, then an {@link UndeclaredThrowableException}
	 *             containing the exception that was thrown by this method will
	 *             be thrown by the method invocation on the proxy instance.
	 * 
	 * @see UndeclaredThrowableException
	 */
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// TODO Auto-generated method stub
		beforeInvoke();

		Object invoke = method.invoke(targetInstance, args);

		afterInvoke();

		return invoke;
	}

	/**
	 * 调用之前
	 */
	private void afterInvoke() {
		// TODO Auto-generated method stub
		System.out.println("after invoke");
	}

	/**
	 * 调用之后
	 */
	private void beforeInvoke() {
		// TODO Auto-generated method stub
		System.out.println("before invoke");

	}

}
4.测试代码:

package glut.test;

import glut.proxy.Bird;
import glut.proxy.IFly;
import glut.proxy.MyProxy;

import java.lang.reflect.Proxy;

import org.junit.Test;

public class MyTest {
	@Test
	public void test() {
		IFly bird = (IFly) Proxy.newProxyInstance(IFly.class.getClassLoader(),
				new Class[] { IFly.class }, new MyProxy(new Bird()));
		bird.fly();
	}

}


5.测试结果:
before invoke

A bird is flying

after invoke
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: