2、代理方法, 先获取目标方法,然后执行InvocationHandler实现的invoke方法
public class ProxyBusiness implements IBusiness, IBusiness2 {
//将Invocationhandler的实现类作为代理类的成员变量
private LogInvocationHandler h;
@Override
public void doSomeThing2() {
try {
Method m = (h.target).getClass().getMethod("doSomeThing", null);
h.invoke(this, m, null);
} catch (Throwable e) {
// 异常处理(略)
}
}
@Override
public boolean doSomeThing() {
try {
//取得目标对象的方法,然后将methoed对象传到invocationHandler.invoke()方法
Method m = (h.target).getClass().getMethod("doSomeThing2", null);
//在invoke的方法中,可以在目标方法前增加, 也可以目标方法后增加
return (Boolean) h.invoke(this, m, null);
} catch (Throwable e) {
// 异常处理(略)
}
return false;
}
public ProxyBusiness(LogInvocationHandler h) {
this.h = h;
}
//测试用
public static void main(String[] args) {
//构建AOP的Advice
LogInvocationHandler handler = new LogInvocationHandler(new Business());
new ProxyBusiness(handler).doSomeThing();
new ProxyBusiness(handler).doSomeThing2();
}
}