package reflect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import static java.lang.System.out;
interface Action // 目标类的实现的接口
{
void say();
void cry();
void smile();
}
interface Advice{ // 在代理执行目标方法之前的建议接口
void beforeMethod();
void afterMethod();
}
class MyAdvice implements Advice // 实现建议的类
{
@Override
public void afterMethod() {
out.println("method start");
}
@Override
public void beforeMethod() {
out.println("method after");
}
}
public class ProxyFactory {
public Object target = null;
public Object bind(final Object target,final Advice advice) { // 得到一个代理,并且在执行目标方法之前执行建议
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
advice.beforeMethod(); // 在执行目标方法之前执行建议
result = method.invoke(target, args);
advice.afterMethod();// 之后 的建议
return result;
}
});
}
public static void main(String args[]) {
Object target = new Action() {
@Override
public void cry() {
out.println("I'm crying...");
}
@Override
public void say() {
out.println("I'm saying...");
}
@Override
public void smile() {
out.println("I'm smiling...");
}
};
Advice myadvice = new MyAdvice();
Action proxy = (Action)new ProxyFactory().bind(target, myadvice);
proxy.cry();
}
}
ProxyFactory
最新推荐文章于 2023-05-13 16:42:46 发布