通过AspectJ了解调用者类 [英] Knowing caller class with AspectJ

查看:73
本文介绍了通过AspectJ了解调用者类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模仿Spring的

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

问题是我需要知道我的消息总线(RabbitMQ MessageListener)是在调用该方法还是该方法将立即返回的普通(所有其他)调用者.

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.

我的注释称为@MQAsync,而不是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;
    }
}

call 切入点将为我提供调用方上下文,但由于我将通过反射使用消息侦听器调用该方法,因此将无法正常工作.执行切入点(注释掉)不会告诉我谁在调用该方法.

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.

是否可以通过某种堆栈转储分析来确定调用方类?

推荐答案

您可以通过以下调用确定哪个类正在调用当前方法.请注意,您将必须捕获 ClassNotFoundException (除非您对只是将名称作为 String 检索而感到满意).

You can determine which class is invoking the current method with the following call. Note that you'll have to catch ClassNotFoundException (unless you're satisfied simply retrieving the name as a String).

Class.forName(Thread.currentThread().getStackTrace()[2].getClassName());

为什么要使用第三个元素?因为在调用堆栈跟踪方法时,堆栈是这样排序的:

Why the third element? Because the stack is ordered like so when the stack trace method is invoked:

  1. Thread#getStackTrace()
  2. CurrentClass.currentMethod ()
  3. ParentClass.parentMethod ()

这篇关于通过AspectJ了解调用者类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆