1

So here´s what I wanna do: I want to log the debit method from the Account class, however, I want to log both the amount (debit parameter) AND the getAccountNumber field from the class.

I´m having trouble on how do I go about to get the class field´s value from within the aspect

public interface Account {
    public int getAccountNumber();
    public void debit(float amount) throws InsufficientBalanceException;
}


public aspect Log { 
    pointcut Logging() : call(* Account.debit()); 

    before() : Logging(){
    }

    after() : Logging(){
    }
}
ch1m3r4x
  • 11
  • 2

1 Answers1

1

You have a couple of options. For targeted logging you could bind the Account instance and parameter value and access the information you need directly:

pointcut Logging(Account account, float amount): call(* Account.debit()) && args(amount) && target(account);

before(Account account, float amount): Logging(account, amount) {
  System.out.println("Number="+account.getAccountNumber()+" Amount="+amount);
}

For more general logging (if you were were perhaps wildcarding more names in your call pointcut) you could use thisJoinPoint (it is a bit like 'this' in that it is a built in name that you can use in an advice block):

pointcut Logging() : call(* Account.debit(..)); 

before() : Logging(){
  System.out.println("Number="+((Account)thisJoinPoint.getTarget()).getAccountNumber();
  // use getArgs() on thisJoinPoint to amount
}

thisJoinPoint is more costly to compute than direct binding. Notice I also changed your pointcut to debit(..) since your debit takes a parameter, the pointcut element you had of debit() won't match that. Also, just to point out a possible improvement, matching 'call' will instrument potentially lots of places (all the calls to the method). Matching on 'execution' of your method will typically match/weave many fewer places, because it matches the destination of the call and many of those calls may be going to the same place. If matching on execution then change the use of target binding above to this.

Andy Clement
  • 2,510
  • 16
  • 11
  • Hi, in my case I need instance , parameter value and also field from interface. how can I add field from interface to pointcut? – Irakli Oct 28 '16 at 16:01