AspectJ Pointcut to introspect a local method code and print a variable inside local method

StackOverflow https://stackoverflow.com/questions/5902274

  •  29-10-2019
  •  | 
  •  

Question

I am trying to write a pointcut and advice which could print a string from following method -

public CustomerDto getCustomer(Integer customerCode){           
           CustomerDto customerDto = new CustomerDto();           
           String emailID =getEmailAddress();
           customerDto.setEmailAddress(emailID);             
           customerDto.setEmployer(getEmployer());
           customerDto.setSpouseName(getSpouse());
           return customerDto;      
}

I am unable to figure out a way by which a pointcut look at String emailID and then print the value of the same in an advice.

Was it helpful?

Solution

Maybe you need something like the following:

public privileged aspect LocalMethodCallAspect {
    private pointcut localMethodExecution() : withincode(public CustomerDto TargetClass.getCustomer(Integer)) && 
        call(private String TargetClass.getEmailAddress());

    after() returning(String email) : localMethodExecution()
    {
        System.out.println(email);
    }
}

Where TargetClass is a class containing getCustomer() and getEmailAddress() methods.

Or the same using @AspectJ:

@Aspect
public class LocalMethodCallAnnotationDrivenAspect {
    @Pointcut("withincode(public CustomerDto TargetClass.getCustomer(Integer)) && " +
            "call(private String TargetClass.getEmailAddress())")
    private void localMethodExecution() {

    }

    @AfterReturning(pointcut="localMethodExecution()",returning="email")
    public void printingEmail(String email) {
        System.out.println(email);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top