I was wondering if there is anyway of determining what method was active when this aspect was triggered. I found the method JointPoint.getSourceLocation() which returns the source code line. I realised I could try to parse that source file and try to determine the method from that… but there seems like there ought to be a better way.
Basically, if has the following code:
class Monkey{
public void feed( Banana b ){
b.eat()
}
}
class Banana{
private static int bananaIdGen;
public final int bananaId = ++bananaIdGen;
private boolean eaten = false;
public void eat(){
if( eaten )
throw IllegalStateException( "Already eaten." );
else
eaten = true;
}
}
I’d like to have an aspect like
@After("call(void Banana.eat()) && target(bbb)")
public void whereEaten( Banana bbb ){
....
}
Where in the body I could print out something like `”Banana 47 eaten by org.example.Monkey(org.example.Banana)”.
The reason is that that I would like to throw an error if a method has been called by a method without a certain annotation on it. For that I’d need to have the Method of the method.
I suppose this question with its
thisEnclosingJoinPointStaticPartcan help you.But the best way to solve your problem is to construct the right join point using
withincodeandcallpointcuts as in example here (seeContract Enforcementsection). This way you prevent calls from methods with or without certain annotation.The list of pointcuts is available here.
What about your sample code lets introduce annotation:
Our
Bananaclass:Our
Monkeyclass with corresponding annotation:Our
Airplaneclass which, of course, can’t eat and so hasn’t@CanEatannotation:Our simple main class for testing:
So we need to avoid eating bananas by Airplane. And the corresponding aspect to obtain this:
So now our test main class produces the right output:
Hope this solves your problem.