malejpavouk
malejpavouk

Reputation: 4445

AspectJ: this and target context

I am using aspectj for analysis of my program. Currently my aspect looks like:

@Aspect
public class InvokeAspect {
    @Before("anyCall(t, s)")
    public void processInvocation(JoinPoint point, JoinPoint.EnclosingStaticPart enclosingStatic, Object t, Object s){
        System.out.println("***");
        System.out.println("Invoker: " + s.toString());
        System.out.println("Invoker: " + enclosingStatic.getSignature().toLongString());
        System.out.println("Invoked object: " + t.toString());
        System.out.println("Invoked: " + point.getSignature().toLongString());
        System.out.println("");
        System.out.println("***");
    }
    @Pointcut("call(* *(..)) && !within(cz.cvut.kbss.odra..*) && target(t) && this(s)")
    public void anyCall(Object t, Object s){}
}

Everything works as expected, but is there any way to convice aspectj to use the aspect, even if this or source do not exist? (static method call or call from static method). Or do I have to write 3 aspects?

Thanks.

Upvotes: 1

Views: 2246

Answers (2)

kriegaex
kriegaex

Reputation: 67297

You can also do it with one pointcut + one advice if you are willing to determine your target and this objects dynamically. I am writing this in AspectJ syntax because I do not feel comfortable with the POJO annotation style:

public aspect InvokeAspect {
    pointcut anyCall() : call(* *(..)) && !within(cz.cvut.kbss.odra..*);

    before() : anyCall() {
        Object s = thisJoinPoint.getThis();
        Object t = thisJoinPoint.getTarget();
        // and so forth
    }
}

Now you can print or log whatever seems appropriate to you. Take care of checking s and t for null values if you want to call methods such as toString() upon them.

Upvotes: 3

Biju Kunjummen
Biju Kunjummen

Reputation: 49915

Yes, I think you will have to write three pointcuts - one along the lines of what you have, second a call from a static method and the third for a call from an object to a static method, probably three different advices also, delegating to the processInvocation method above

Upvotes: 0

Related Questions