通过AOP获取响应对象的名字

Get the name of the response object through AOP

使用 AOP 我知道使用 java 8 和切入点现在可以通过 AOP 获取方法方法参数的名称。

我的问题是,是否也可以获取正在 returned 的对象的名称?

更新 - 添加代码示例:

我正在尝试记录从方法return编辑的对象的名称

    /**
     * Log the return value of all methods in the package service.impl
     * @param pjp
     * @param returnValue
     */
    @AfterReturning(pointcut = "execution(public * com.bla.core.service.impl.*.*(..))", returning = "returnValue")
    public void debugAfter(JoinPoint pjp, Object returnValue) {
        if (logger.isDebugEnabled()) {
            logger.debug(getAuditEndMessage(pjp, returnValue));
        }
    }


    private String getAuditEndMessage(JoinPoint joinPoint, Object returnValue) {
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getSimpleName();

        //Assuming every object has the toString method overriden
        //In reality there is more logic than this
        String returnValueStr = String.valueOf(returnValue);

        String returnValueObjectName = //Trying to find some way of finding this value

        //Ex: "[End][CategoryServiceImpl][getCategory]Ouput: [category=[id=1][name=Test Category][description=Test Description]]
        String returnStr = "[End][" + className + "][" + methodName + "]Ouput: [" + returnValueObjectName + "=" + returnValueStr + "]"

        return returnStr;
    }

所以如果我有一个方法:

    public ExampleCategory getCategory(int categoryId){
        ExampleCategory category = exampleCategoryDao.read(categoryId);
        return category;
    }

我希望输出字符串包含正在 returned 的对象的名称:

[结束][CategoryServiceImpl][getCategory]输出:[类别=[id=1][name=测试类别][description=测试描述]]

我可以使用新的 java 8 功能获取输入参数的名称,但我不知道如何使用 return 值。

更新二:

打完这些之后,我意识到如果这是可能的,也可能会有奇怪的情况,比如:

    public ExampleCategory getCategory(int categoryId){
        return exampleCategoryDao.read(categoryId);
    }

在这些情况下,我可以只打印 returning class 名称。我仍然想知道是否可以按照我上面的要求做。

正如我在 that answer 中所说的,AspectJ 不了解局部变量,只了解 non-static 或静态成员变量。所以你的问题的答案是否定的。

即使那是可能的,我也看不出知道局部变量名有任何附加价值。你远远超出了 AOP 的概念(实现 cross-cutting 关注),而是在调试器的范围内。此外,local 变量的概念(甚至这个术语本身!)都是关于它们的位置的。除了方法之外,它们不是 class 契约的一部分,而是完全在其实现内部。

顺便说一下,建议名称 @AfterReturning 暗示了它的目的:获取一些信息并在 方法返回结果后做一些事情。您想知道 returns 结果之前的一些内部方法状态。