问题描述
是否可以使用around通知取消方法的执行并在方面的方法内执行它?
Is it possible to cancel a method's execution with around advice and execute it inside a method in the aspect?
示例:我们有一个项目:
Example :we have a project that has:
1 - 活动 SenderActivity.java.在此活动中,我们有一个方法 MethodA(),它返回 String.
1 - An activity SenderActivity.java . Inside this activity we have a method MethodA() which returns String.
喜欢:
public static String MethodA(){
String string = "a string";
return string;
}
2 - 我们使用 aspect.aj 中的切入点捕获 MethodA() 的执行
2 - We catch MethodA() 's execution with a pointcut inside the aspect.aj
喜欢:
pointcut pointcut_catchMethodA() : execution(static String MethodA());
周围的建议是:
String around() : pointcut_catchMethodA(){
//We return null or simply don't call the proceed()
return null;
}
所以在这里,每次尝试执行 MethodA() 时,around 通知都会取消它.
So here, everytime MethodA() is tried to be executed, around advice cancels it.
我想知道在取消之后,我是否可以做一些类似的事情:
And I'm wondering if after this cancellation, can I do something like :
public void MethodToCallMethodAInsideTheAspect(){
SenderActivity.MethodA();
}
因此,通过这种方式,我取消了对 MethodA() 的原始调用,并在我的 aspect.aj 中手动调用了它.所以我希望 MethodA() 返回它的原始值.(string = "a String").
So by this way, I cancelled the original call to MethodA() and I called it manually inside my aspect.aj. So I want MethodA() to return it's original value. (string = "a String").
有可能吗?或者,如果有一种方法可以实现这一点,那么请不要犹豫您的指导.
Is it possible ? Or if there is a way to implement this, then please don't hesitate your guidance.
因为我尝试了这种实现,当我想手动执行 SenderActivity.MethodA() 时,我的实现返回了空值.我认为它围绕建议的价值返回.
Because I tried this kind of implementation and my implementation returned null value when I want to execute SenderActivity.MethodA() manually. I think it returns around advice's value.
推荐答案
我自己找到了解决方案:
I've found the solution by myself :
这个架构确实有效,它只需要替换切入点:
This architecture actually works, it has to be replaced just the pointcut :
来自
pointcut pointcut_catchMethodA() : execution(static String MethodA());
到:
pointcut pointcut_catchMethodA() : call(static String MethodA(..)) && !within(Aspect);
在这里,我们使用 inside 是因为我们不希望我们的切面捕捉到从切面发出的调用,即
here, we use within because we don't want our aspect to catch calls that has been made from the aspect i.e.
public void MethodToCallMethodAInsideTheAspect(){
SenderActivity.MethodA();
}
所以这个调用不会被环绕通知捕获.因此,对 MethodA() 的原始调用已被周围通知取消,并由 MethodToCallMethodAInsideTheAspect() 手动调用
So this call will not be catched by around advice. So the original call to MethodA() has been cancelled by around advice and it's called manually by MethodToCallMethodAInsideTheAspect()
这篇关于使用around通知取消方法执行并在方面内部手动执行此方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!