Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knowing caller class with AspectJ

I'm trying to imitate Spring's AspectJ @Async support but with a message bus.

The issue is I need to know if my Message Bus (RabbitMQ MessageListener) is calling the method or a normal (all others) caller where the method will return instantly.

My annotation is called @MQAsync instead of Springs @Async.

package com.snaphop.mqueue;

import org.apache.log4j.Logger;
import com.snaphop.mqueue.MQAsync;

public aspect MQAsyncAspect {

    //pointcut asyncTypeMarkedMethod() : execution(@MQAsync void *(..));
    pointcut asyncTypeMarkedMethod() : call(@MQAsync void *(..));

    private static final Logger log = Logger.getLogger("MQAsync");

    Object around() : asyncTypeMarkedMethod() {     
        if (listenerIsCaller) {
            return proceed();
        }
        //Send the method parameters to the message bus.
        //this logic isn't here for brevity.
        return null;
    }
}

The call pointcut will get me the caller context but that will not work as I will be calling the method with my message listener through reflection. The execution pointcut (commented out) will not tell me who is calling the method.

Is there a way to determine the caller class maybe through some sort of stack dump analysis?

like image 769
Adam Gent Avatar asked Dec 01 '22 22:12

Adam Gent


1 Answers

Actually cheeken's answer is nice, but for AspectJ call() pointcuts you can get the calling class much more easily and without ugly reflection:

thisEnclosingJoinPointStaticPart.getSignature().getDeclaringType()

Please consider to accept this answer if you think it is better than the other one, otherwise just enjoy the power of AspectJ. ;-)

like image 128
kriegaex Avatar answered Dec 11 '22 09:12

kriegaex