先附上项目结构:
步骤:
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();
}
}
before invoke
A bird is flying
after invoke