public interface MyTargetInterface {
public void sayHello();
}
public class MyTarget implements MyTargetInterface {
public void sayHello() {
System.out.println("welcome to the struts world!");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyHandler implements InvocationHandler {
private Object obj;
public void setObj(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("before invoke the method...");
method.invoke(obj, args);
System.out.println("after invoke the method...");
return null;
}
}
import java.lang.reflect.*;
public class MyProxy {
public Object getMyProxy(Object obj,InvocationHandler target) {
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), target);
}
}
public class Client {
public static void main(String[] args) {
MyTargetInterface mytarget = new MyTarget();
MyHandler myhandler = new MyHandler();
myhandler.setObj(mytarget);
MyProxy myproxy = new MyProxy();
MyTargetInterface proxy = (MyTargetInterface)myproxy.getMyProxy(mytarget, myhandler);
proxy.sayHello();
}
}
代理模式+拦截器
最新推荐文章于 2020-10-14 16:17:14 发布