Pages

Saturday, August 14, 2010

AspectJ - Pointcut and Advices for methods with more than one arguments

I am still doing my Masters in computer science and have worked on many new technologies like javaFX, Jasper Reports etc. But, I have not had time to update my blog on any of these. I was working on AspectJ for another project for my course, only to realize that Google is not able to find a blog that provides me the syntax to use Poitcut with parameters when there are more than one arguments to a method for which the join point is being defined. After lot of frustration, I found the solution in trial and error method. The AspectJ documentation only provides the trivial examples with functions having one arguments, for example - a setter. I went through a AOP textbook and even that failed to provide me this solution. Hopefully, this piece of information will come in Google search if anyone is searching solution of exact or similar problem. Since, its my school project I cant put the real code and project on the blog. I will consider a dummy situation here. Lets say that there exists a Class named Transaction, and there exist a method doInsert as shown below.

public class Transaction{
public Boolean doInsert(Integer accountNumber, Double amount){
//.
//.
//.
return boolVal;
}
}


To define a point cut for the same, the below aspect can be used.



public aspect TransactionAspect {
pointcut t1(Transaction t, Integer accountNumber) :
target(t) && args(accountNumber,..) &&
execution(* *(Integer,..));


before(Transaction t, Integer accountNumber) : t1(t, accountNumber){
if(!isDoAbleForAccount(t,accountNumber)){
throw new RuntimeException("Error : Detected error before transacting");
}
}
private boolean isDoAbleForAccount(Transaction t,Integer accountNumber){
//
//
}
}


The above aspect defines a pointcut named t1 with 2 parameters. The first parameter is the Transaction object itself which is the target object in execution, the second parameter is an Integer account number that is passed as an argument to the doInsert method. Note the syntax of the "args" in the pointcut. It has one to one mapping to the execution pattern "* *(Integer,..)" which defines any method, with any return value, but 1st argument as Integer and any number of remaining argument. The before advice uses this pointcut, and the remaing code is just not that important.

There is a one to one mapping for arguments between the "args" and the pattern used to select method's from a target object.