You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用AspectJ获取@Step注解方法的所属类名?

问题描述

我有一个包含@Step(io.qase.api.annotation.Step)注解方法的类myStepsClass,代码如下:

class myStepsClass() {

    @Step
    fun stepOne() {***}

    @Step
    fun stepTwo() {***}
}

我希望这些方法执行时,打印出Step Called: myStepsClass -> stepOne这类包含类名+方法名的格式,但当前的AspectJ切面只能输出方法名。现有切面代码如下:

@Aspect
class Aspects {

    @Before("@annotation(io.qase.api.annotation.Step)")
    fun stepMethod(joinPoint: JoinPoint) {
        println("Step called: ${getMethodName(joinPoint)}")
    }

    private fun getMethodName(joinPoint: JoinPoint): String {
        val methodSignature = joinPoint.signature as MethodSignature
        return methodSignature.name
    }
}
解决方案

要实现需求,只需要在切面中获取方法所属的类名,再和方法名拼接即可,有两种可靠方式:

方式一:通过目标对象获取类名

直接从JoinPoint的target属性获取执行方法的对象所属类的名称:

@Aspect
class Aspects {

    @Before("@annotation(io.qase.api.annotation.Step)")
    fun stepMethod(joinPoint: JoinPoint) {
        // 获取类的简单名称(不带包名)
        val className = joinPoint.target.javaClass.simpleName
        val methodName = getMethodName(joinPoint)
        println("Step Called: $className -> $methodName")
    }

    private fun getMethodName(joinPoint: JoinPoint): String {
        val methodSignature = joinPoint.signature as MethodSignature
        return methodSignature.name
    }
}

方式二:通过方法签名获取类名

从MethodSignature中直接获取方法声明所在的类信息,这种方式不依赖目标对象实例,静态方法场景下也能正常使用:

@Aspect
class Aspects {

    @Before("@annotation(io.qase.api.annotation.Step)")
    fun stepMethod(joinPoint: JoinPoint) {
        println("Step Called: ${getClassAndMethodName(joinPoint)}")
    }

    private fun getClassAndMethodName(joinPoint: JoinPoint): String {
        val methodSignature = joinPoint.signature as MethodSignature
        // 获取类的简单名称
        val className = methodSignature.declaringType.simpleName
        val methodName = methodSignature.name
        return "$className -> $methodName"
    }
}

补充说明

  • 如果需要输出全类名(比如com.example.myStepsClass),只需把simpleName替换为name即可
  • 两种方式都能实现需求,可根据实际场景选择:如果都是实例方法,方式一更直观;如果包含静态方法,方式二更稳妥

内容的提问来源于stack exchange,提问作者mikamika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:24:31