Shraddha
Shraddha

Reputation: 2335

Get target Object in Aspect and call another method on target object

I want to write an aspect on a method pointcut, and in the aspect I want to call another method using the object on which pointcut method is called.

Something like this:


@Pointcut("@annotation(com.mypackage.Notify(getC))")
public void notifyPointCut() {
}

@AfterReturning(value = "notifyPointCut(getC)", argNames = "joinPoint") 
public void notifyChange (JoinPoint joinPoint) {
  Object targetObject  = joinPoint.getTarget();
  C cField = targetObject.invokeMethod("getC");
  notifier.sendUpdate(cField);
}

I want to get the object on which joinPoint method is called and make another method call on that object (method name that is passed in the annotation)

My use case is to get some fields of the object, these fields are created or updated by joinPoint method. Once joinPoint method returns, I want to get those fields in the aspect and send a notification on the field value.

I am not sure if I am complicating aspect usage too much as I could not find such a usage anywhere on searching.

Upvotes: 2

Views: 8907

Answers (1)

Shraddha
Shraddha

Reputation: 2335

I figured out how to invoke the method. I need to get the method and invoke it, then I do not need to do casting for the class.


Object targetObject  = joinPoint.getTarget();
Method m = targetObject.getMethod("getC");
m.invoke(targetObject);

Upvotes: 3

Related Questions