用一个例子演示一个动态代理过程,提供参考。
1.定义接口
//IUserBean.java
public interface IUserBean {
public void getUser();
public void addUser();
public void updateUser();
public void deleteUser();
}
2.实现接口
//UserBean.java
public class UserBean implements IUserBean {
public UserBean() {
}
public void addUser() {
System.out.println("addUser() invoked");
}
public void deleteUser() {
System.out.println("deleteUser() invoked");
}
public void getUser() {
System.out.println("getUser() invoked");
}
public void updateUser() {
System.out.println("updateUser() invoked");
}
}
3.Proxy对象,负责生产代理类
//AuthorProxy.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class AuthorProxy implements InvocationHandler {
private Object o = null;
public Object createProxyObject(Object o)
{
this.o = o;
return Proxy.newProxyInstance(this.o.getClass().getClassLoader(),
this.o.getClass().getInterfaces(), this);
}
public Object invoke(Object obj, Method method, Object[] args)
throws Throwable {
Object ret = null;
System.out.println("check author before invoke");
if(this.o!=null)
ret = method.invoke(this.o, args);
System.out.println("check author after invoke");
return ret ;
}
}
5.请求代理类生成UserBean代理对象,拦截方法调用过程。
//ProxyDemo.java
public class ProxyDemo {
public static void main(String[] args) {
UserBean userBean = new UserBean();
AuthorProxy ap = new AuthorProxy();
IUserBean iu = (IUserBean)ap.createProxyObject(userBean);
iu.updateUser();
}
}