一.简介
在不修改原业务的基础上,基于原业务方法,进行重新的扩展,实现新的业务。
二.结构
参考《疯狂Java讲义》
三.示例
public class MyPerson implements PersonInterface {
@Override
public void doSomeThing() {
System.out.println("doSomeThing");
}
@Override
public void saySomeThing() {
System.out.println("saySomeThing");
}
private void test(){ System.out.println("private test"); }
}
public interface PersonInterface {
void doSomeThing();
void saySomeThing();
}
public static void main(String[] args) {
final MyPerson p = new MyPerson();
PersonInterface proxy = (PersonInterface) Proxy.newProxyInstance(MyPerson.class.getClassLoader(), MyPerson.class.getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开始");
if (Objects.equals(method.getName(), "saySomeThing")) {
System.out.println("等待saySomeThing");
p.saySomeThing();
} else {
Object invoke = method.invoke(p, args); // 调用任何public方法都拦截
System.out.println("结束");
}
return null;
}
});
proxy.doSomeThing();
proxy.saySomeThing();
}
结果:
开始 doSomeThing 结束 开始 等待saySomeThing saySomeThing